Search code examples
javascriptvuejs3vuelidate

vuelidate identical passwords only if checkbox is ticked


I have one form for logging in and creating an account. Additional fields are added when a checkbox is ticked.

<label for="createNewAccount" >Create account
  <input v-model="form.createNewAccount" type="checkbox" name="createNewAccount">
</label>

This returns a boolean value.

data () {
    return {
      form:{
        admEmail: '',
        admPassWord: '',
        confPassWord: '',
        createNewAccount: false,
      }
    }
  },

I'm using vuelidate, but the sameAs built-in validator must run only if this.form.createNewAccount === true.

this works (but I don't see how to introduce the requirement that this.form.createNewAccount must be true for this to run):

confPassWord: {
  myFunction: helpers.withMessage(
    `La confirmation ne correspond pas au mot de passe.`,
     sameAs(this.form.admPassWord)
   )
}

I tried this:

validations () {
  return {
    form: {
      confPassWord: {
          myFunction: helpers.withMessage(
            `La confirmation ne correspond pas au mot de passe.`,
            (value) => { 
              if (this.form.createNewAccount === true) {
                value === this.form.admPassWord
              }
              return true       
            }
          )
        }

console.log(value + this.form.admPassWord returns the right values.

I expect this function to run only when this.form.createNewAccount === true and to always return true otherwise and to return false when value === this.form.admPassWord returns false.

But : it always passes validation, including when this.form.createNewAccount is true and the passwords don't match.


Solution

  • The most concise fix is:

            (value) => { 
              return !this.form.createNewAccount || value === this.form.admPassWord;      
            }
    

    A more readable fix is:

            (value) => { 
              return this.form.createNewAccount ? value === this.form.admPassWord : true;      
            }