Vuetify Form Validation - defining ES6 rules for matching inputs

sternmd picture sternmd · Nov 10, 2017 · Viewed 16.6k times · Source

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

Answer

Eiji Shinjo picture Eiji Shinjo · Jul 23, 2018

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.