ā† Go Back

Writing Custom Vee-Validate Rules in Your Vue Js Projects

I recently had a problem. I wanted to validate an input field using a custom rule, but it took longer than it should because I didnā€™t get the necessary resources to guide me. This tutorial will try to solve that problem.

Vee Validate allows us to extend its in-built rules. It has various ways of implementing this, but the most common one is using the extend method with an object as its argument that contains a message property and a validate method.

Example of the extend method
extend('name_of_custome_rule', {
message: "Error message for our custom rule {_field _}",
validate: value => {
return "Condition that evaluates to true of false"
}
})
view raw extend.js hosted with ❤ by GitHub

The extend method takes the name of the custom rule as the first argument and an object as the second.

The object has a message property which can access the field which is under validation using the {_field_} syntax. The object has a validate method that's passed an argument by default. This is the value to be validated and is gotten from the input field. The validate method on the object returns either a boolean, an object or a promise. When it returns an object, the valid property must be present and be a boolean value. The value will then be checked to see if the form input has a valid value or not.

Letā€™s put it into Action.

We are going to create a custom password validator with vee-validate.

A vee validate rule for custom passwords
import { extend } from "vee-validate"; //import extend function from vee-validate
extend("password", {
message:
"{_field_} must be at least 8 characters, contain One Uppercase, One lowercase, One Special character i.e (! @ # $ % ^ & *), One number.",
validate: value => {
const strong_password = new RegExp(
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})"
); // regex to check our strong password
return strong_password.test(value); //Test the regex. Test function returns a true or false value.
}
});
view raw custom.js hosted with ❤ by GitHub

Ā Ā  Ā 

Result of ValidatorResult of Validator

Conclusion

I hope you have now learnt how to create custom validation rules with VeeValidate. To explore the options in details, you can visit the official documentation here