Search code examples
javascriptvalidationvue.jsvuelidate

How to implement requiredUnless validator of vuelidate for checkboxes


Using Vuelidate, since 'required' validator now considers boolean 'false' a valid value, you have to use 'sameAs' like sameAs: sameAs( () => true ) to implement required validation for checkboxes. How to implement 'requiredUnless' validation for checkboxes using vuelidate where checkbox is only required to be checked if a property is not a certain value?


Solution

  • false is validate as valid so you need to change it to an empty string, I'll do this in watch:

        data() {
            return {
                email: '',
                age: null,
                password: '',
                confirmPassword: '',
                country: 'Malta', 
                hobbyInputs: [],
                terms: '',
                countries,                
            }
        },        
        validations: {
          terms: {
            required: requiredUnless(vm => {
              return vm.country === 'Malta'
            }),
          }
        },
        watch: {
          terms() {
            if (!this.terms) {
              this.terms = '';
            }
          }
        },