The customer is king
and this also applies to the world of software. But there are also rules for the customer. For example, in a store or on the train, you have to make sure that the mouth-nose cover also - who would have thought it - covers the nose.
We also expect visitors on our website and users of our application to follow certain rules. For example, if we need to collect personal information for our insurance or lottery companies, we are happy if Jane Doe does not enter a mosaic of special characters as her city of residence and her date of birth is at least a few years before the date of entry, at least as long as time travel is still fiction.
If Jane doesn't follow the rules and her data differs from what we can expect and process, we can give Jane clues to explain what she has done wrong. This mechanism of form validation is not only important for us, but for all websites and apps that require information and/or confirmation from users. So that we as developers don't have to reinvent the wheel every time, there are libraries for it. Behind the third VueCember-door there was already an article about VeeValidate, today we'll have a look at Vuelidate.
Vuelidate also offers built-in validation rules, can easily be extended with rules from other libraries (like Moment.js or date-fns for date validations) and allows to add your own rules. Unlike VeeValidate, Vuelidate does not require the data to be validated to use form input binding with v-model. This makes it more suitable for validating other reactive data like computed properties. Another special feature of Vuelidate is that it is model-based. This means that it appears separately from the template and the rest of the code as a validation object called validations, which reflects the data structure of what we want to validate. This way the template remains clear, especially for complex forms that have many fields and maybe even dependencies between the fields. Our validations are all collected and easily readable in one place in the corresponding file.
This looks like this, for example:
validations: %7B insuranceStart: %7B required, isValidDate, %7D, policyHolder: %7B required, address: %7B zip: %7B required, %7D, city: %7B required, %7D, %7D, %7D, insuredPersons: %7B required, $each: %7B dob: %7B required, isValidDate, isInPast, isAboveMinAge: isAboveMinAge(18), %7D, %7D, %7D, %7D
In the Vue-Devtools we find the computed property
$v. This provides us with information about Jane's previous interaction with the form in general and with all fields to be validated.
$invalid represent the current state of the validation. This can look something like this example of CSS-Tricks, where we only have
name as specification and nothing has been entered into the input field yet:
tl;dr? For the setup of Vuelidate in your project click here.