Creating a custom rule in Vue Vee-Validate

Rafa Rafael
2 min readMar 7, 2020

--

A powerful form validation for vue.js. It is easy touse and amazingly fast. But there are situations that I needed to create custom rules as we have forms that has a unique rule and not available in vee-validate.

But you can add them easily.

First thing first

I already used the Vee-Validate version 3.x so if you are still in version 2.x, I suggest to migrate now as we did and enjoy the big improvement in performance.

My folder structure looked like this

-js
-components
-validators (This hold all vee-validate related files)
-index.js
-utils.js
-rules (This hold all custom rules)

And on this example I added two custom rules that compares a two dates which checks the value of selected date(s) is early or beyond to the subject date.

Get your hands dirty!

First, create a folder name validators and a js file named index.js which holds the instantiation of rules that we wanted to extend and added.

js/validators/index.js

I included some of out of the box rules from vee-validate to show you how easy to add rules.

The {dateType} parameter from my is_beyond and is_earlier custom rules is for you able to insert what kind of date you are validating. e.g Expiration Date.

Custom rules

Then, create a folder under validators named rules and a js file named date_compare.js. This is where the validation happens. So basically the rule I created can accept a Date, an Array of dates and a string date.

js/validators/rules/date_compare.js

And then since I am using vue.js with Laravel, I added the import statement in app.js to initialize the validators.

Then you can now use the custom rule in ValidationProvider component like this

<ValidationObserver ref="formObserver" v-slot="{ validate }">
<ValidationProvider
ref="datePicker"
:rules="`is_earlier:${dateFrom},the Expiration Date.`"
v-slot="{ errors }"
>
//YOUR DATEPICKER CODES... <small
class="block md:text-right text-red mt-2"
v-if="errors[0]"
>
{{ errors[0] }}
</small>
</ValidationProvider>
</ValidationObserver>

Or if you want to use the same rule many times, you can do it like this

Bonus!

I included my custom helpers in case you may want to use the custom rule I created.

js/validators/utils.js

Enjoy!

--

--

Rafa Rafael
Rafa Rafael

Written by Rafa Rafael

Dad / Husband / Full Stack Developer / Lifelong Learner

Responses (1)