Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate vuetify textfield only on submit

temp.vue

<v-form ref="entryForm" @submit.prevent="save">
  <v-text-field label="Amount" :rules="numberRule"r></v-text-field>
  <v-btn type="submit">Save</v-btn>
</v-form>

<script>
export default {

   data: () => ({
     numberRule: [
       v => !!v || 'Field is required',
       v => /^\d+$/.test(v) || 'Must be a number',
     ],
   }),

   methods: save () {
     if (this.$refs.entryForm.validate()){
       //other codes
     }
   }
}
</script>

enter image description here

What happens here is while typing in the text field itself the rule gets executed. I want to execute the rule only on submit. How to do that in vuetify text field?

like image 695
vinieth Avatar asked Aug 18 '19 18:08

vinieth


2 Answers

If you're like me and just want to prevent validation from running on every key stroke, apply validate-on-blur prop on your text fields and now validation will only be perform after user has completed typing the whole input.

So not an exact answer to the OP, but I think this is what most of us want to achieve. This prop has been documented here.

like image 105
dotNET Avatar answered Nov 16 '22 08:11

dotNET


Vuetify rules are executed when the input gets value, But if you want that to happen only on the form submit, you have remodified the rules that are being bound to that input,

Initially, rules should be an empty array, when you click on the button you can dynamically add/remove the rules as you wanted, like this in codepen

CODEPEN

<div id="app">
  <v-app id="inspire">
    <v-form ref="entryForm" @submit.prevent="submitHandler">
      <v-container>
        <v-row>
          <v-col
            cols="12"
            md="6"
          >
            <v-text-field
              v-model="user.number"
              :rules="numberRules"
              label="Number"
              required
            ></v-text-field>
          </v-col>
        </v-row>
        <v-row>
          <v-btn type="submit" color="success">Submit</v-btn>
          </v-row>
      </v-container>
    </v-form>
  </v-app>
</div>

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    valid: false,
    firstname: '',
    user: {
      number: ''
    },
    numberRules: []
  }),
  watch: {
    'user.number' (val) {
      this.numberRules = []
    }
  },
  methods: {
    submitHandler () {
      this.numberRules = [
        v => !!v || 'Field is required',
        v => /^\d+$/.test(v) || 'Must be a number',
      ]
      let self = this
      setTimeout(function () {
        if (self.$refs.entryForm.validate()){
         //other codes
          alert('submitted')
        }  
      })

    }
  }
})
like image 17
Subash Avatar answered Nov 16 '22 06:11

Subash