Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if v-text-field has success state ( or any rule failed )?

I have a component holding input controls ( e.g. v-text-field ). This component provides some props, e.g. the field rules for the input. Whenever the input value passes every rule / enters the success state I want to call a function.

Given the following sample code

Reproduction link

<template>
  <v-app>
    <v-main>
      <v-text-field v-model="msg"
                    :rules="[ v => v.length > 0 || 'required' ]"
                    @update:model-value="onInput"
      />
    </v-main>
  </v-app>
</template>

<script setup>
import { ref } from 'vue'

const msg = ref('')

function onInput(newValue) {
  if(true /* text-field has success state => do things */) {
    console.log(newValue);
  }
}
</script>

How can I check if this field passed every rule? I wasn't able to find an event in the docs

I think it would be slow to run each rule function again.

like image 397
baitendbidz Avatar asked Oct 13 '25 00:10

baitendbidz


1 Answers

Place a ref on the element. And watch its error value:

<template>
  <v-text-field ref="input" />
</template>
<script setup>
import { ref, watch } from 'vue'

const input = ref(null)
watch(() => input.value?.error, (val) => {
  if (val) {
    // input not valid
  } else {
    // input is now valid
  }
})

See it here.

Notes:

  • uncomment <pre v-text="JSON.stringify(input, null, 2)"></pre> to see everything <v-text-field> has to offer.
  • watch is, by default, lazy. Meaning it won't be checked when the component is mounted. If you want to make this check when the component has mounted, pass a third param to it:
    { immediate: true }.
like image 114
tao Avatar answered Oct 16 '25 13:10

tao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!