vuelidate / vuelidate

Simple, lightweight model-based validation for Vue.js
https://vuelidate-next.netlify.app/
MIT License
6.88k stars 497 forks source link

Fire Validator only if the field is populate #389

Open pathum-kalhan opened 6 years ago

pathum-kalhan commented 6 years ago

I have a vuelidate custom validator for validate the mobile number.

const mobile_number_validator = value => {
  let mobileRegx = /^\+94[0-9]{9}$/;
  return mobileRegx.test(value);
};

In my validation object

validations: {
    contact_number: { mobile_number_validator },
  },

I disable the create customer button if something wrong in the validations.

<v-btn
:disabled="$v.$invalid">
    create customer
</v-btn>

contact_number is not a must to create a customer. But the problem here is $v.$invalid is always true if I leave the contact_number field empty.

What I want is

If(You enter a contact number){
    fire `mobile_number_validator` 
}
else{
    do nothing
}

If I further explain I want to validate mobile number only if the your provide a number. Otherwise my custom validatetor mobile_number_validator should not involve in the validation process. Is this possible to achieve?

HoraceKeung commented 6 years ago

Maybe update mobileRegx, so it allows empty string/null/undefined? I am not so good at regex, so not sure what mobileRegx currently doing, but maybe its test return false if contact_number is empty?

Edit: Try: return value ? mobileRegx.test(value) : true;