Skip to content

Custom validation

Oscar edited this page Sep 28, 2018 · 6 revisions

To create a custom validator just give any non existing name and define it as a function that receives three parameters, current vue component, the value to check, and a callback.

data: () => ({
   fullName: null
}),

validations: {
   fullName: {
      required: true,
      nameValid: (vm, value, callback) => {
         let error;

         if (value.indexOf(' ') === -1) {
           error = 'Use first and last name';
         }

         callback(error);
      };
   }
}

In the callback just call it when validation is finished, with an empty value if validation success or with a string message of the error.

If you have custom validators that are used frequently you can just add them the following way:

validations: {
   login: {
      email: { required: true, type: 'email', hasLetter: 'a' },
   }
},

customValidators: {
   hasLetter: function(rules, value, data, vmv) {
      if (value.indexOf(rules.hasLetter) !== -1)
         return;

      return 'Letter '+ rules.hasLetter +' not found';
   }
}

Parameters

Name Description
rules The object rules defined for the variable, { required: true, type: 'email', hasLetter: 'a' } in the previous case
value Is the current value of the variable
data Is the whole data object of vue component, useful if you want to interact with other values
vmv Is the core of the validations which manages, watches and validates the rules, used here mostly to get the error messages
Clone this wiki locally