Vuetify Form Validation - defining ES6 rules for matching inputs

Viewed 23015

I have a (Vuetify) form with an email input that uses ES6 & regex to check if it's a valid email. How would I set up another emailConfirmationRules ruleset to check if the emailConfirmation input matches the email input?

<template>
  <v-form v-model="valid">
       <v-text-field label="Email Address"
            v-model="email" 
            :rules="emailRules"
            required></v-text-field>

       <v-text-field label="Confirm Email Address"
            v-model="emailConfirmation" 
            :rules="emailConfirmationRules"
            required></v-text-field>
   </v-form>
 <template>

export default {
    data () {
      return {
         valid: false,
         email: '',
         emailConfirmation: '',
         emailRules: [
             (v) => !!v || 'E-mail is required',
             (v) => /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'
        ],
        emailConfirmationRules: [
            (v) => !!v || 'Confirmation E-mail is required',
        ]   (v) => ??? || 'Confirmation E-mail does not match'
    }
}
5 Answers

Rules are not the proper way of handling field confirmation. emailConfirmationRules are triggered only when emailConfirmation changes, but if you change email again, your fields won't match anymore without any break of rules.

You have to handle this manually:

methods: {
  emailMatchError () { 
    return (this.email === this.emailConfirmation) ? '' : 'Email must match'
  }
}
<v-text-field v-model='emailConfirmation' :error-messages='emailMatchError()'></v-text-field>

There may be an alternative way of doing this with vee-validate too.

You can accomplish the same with a computed rule.

computed: {
    emailConfirmationRules() {
      return [
        () => (this.email === this.emailToMatch) || 'E-mail must match',
        v => !!v || 'Confirmation E-mail is required'
      ];
    },
}

  emailConfirmationRules: [
    (v) => !!v || 'Confirmation E-mail is required',
    (v) => v == this.email || 'E-mail must match'
  ],
  <template>   
    <v-text-field
      v-model="employee.email"
      :rules="emailRules"
      required
      validate-on-blur
      />
</template>

<script>
data() {
    return {
    emailRules: [
        v => !!v || "E-mail is required",
        v =>
          /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) ||
          "E-mail must be valid"
      ],
}
</script>

Check this post https://stackoverflow.com/a/58883995/9169379

<template>
  <v-input  v-model="firstPassword" />
  <v-input :rules=[rules.equals(firstPassword)] v-model="secondPassword" />
</template>

<script>    
  data() {
  firstPassword: '',
  secondPassword: '',
    rules: {
      equals(otherFieldValue) {
        return v =>  v === otherFieldValue || 'Not equals';
      }
    }
  }
</script>

Related