Home > other >  Show different message on Password validation in Vuetify?
Show different message on Password validation in Vuetify?

Time:04-30

I have passowrd rule like this

passwordRule(value){
 const pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})/;
          return (
            pattern.test(value) ||
            "Min. 8 characters with at least one capital letter, a number and a special character."
          );
}

which I am using currently in

 <v-text-field
            autocomplete="current-password"
            :value="userPassword"
            label="Enter password"
            :append-icon="value ? 'mdi-eye' : 'mdi-eye-off'"
            :type="value ? 'password' : 'text'"
            :rules="[passwordRule]"
          ></v-text-field>

as it currently shows "Min. 8 characters with at least one capital letter, a number and a special character." as error message,

How can I achieve like if password doesn't have capital letter it should display only message like "Atleast 1 capital letter". and if password doesn't have a number it should display "a number is required"

Please guide me how can I achieve that?

CodePudding user response:

Your current rule assumes that the password must contain only latin uppercase letters.

If it's OK, use uppercaseEn rule from code below. Otherwise it should be better to use uppercase rule.

<v-text-field
  v-model="password"
  :rules="[rules.uppercaseEn, rules.special, rules.number, rules.length]"
  label="Password"
></v-text-field>
...
data () {
  return {
    password: '',
    rules: {
      uppercase: value => {
        //For non-latin letters also
        return (value && value.toLowerCase() !== value) || 'At least 1 uppercase letter'
      },
      uppercaseEn: value => {
        //For latin letters only
        return /[A-Z]/.test(value) || 'At least 1 uppercase letter (A-Z only)'
      },
      number: value => {
        return /\d/.test(value) || 'At least 1 number'
      },
      special: value => {
        return /[!@#\$%\^&\*]/.test(value) || 'At least 1 special symbol'
      },
      length: value => {
        return (value && value.length >= 8) || 'Min password length: 8 symbols'
      }
    },
  }
}

Test this at CodePen.

  • Related