Search code examples
vue.jsvuejs2vuetify.js

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?


Solution

  • 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')
            }  
          })
    
        }
      }
    })