Vuejs 2 + form validation
Solution 1
In my opinion, a good way to implement front end validation for VueJS is to use vuelidate.
It's very simple to use and powerful. It offers model-base validation, it means that it's what you define in data that is validated, so it's totally decoupled from the templates. It comes with common built-in validators for email , min and max length or required. And many others.
Solution 2
Since it's all ultimately Javascript, you could also use some of the existing Javascript validation libraries like Parsely.js or Validate.js to hook this up. One thing that's nice about the Validate.js library is that it's format could easily be stored in the global store if you're using Vuex:
var constraints = {
creditCardNumber: {
presence: true,
format: {
pattern: /^(34|37|4|5[1-5]).*$/,
message: function(value, attribute, validatorOptions, attributes, globalOptions) {
return validate.format("^%{num} is not a valid credit card number", {
num: value
});
}
},
length: function(value, attributes, attributeName, options, constraints) {
if (value) {
// Amex
if ((/^(34|37).*$/).test(value)) return {is: 15};
// Visa, Mastercard
if ((/^(4|5[1-5]).*$/).test(value)) return {is: 16};
}
// Unknown card, don't validate length
return false;
}
},
creditCardZip: function(value, attributes, attributeName, options, constraints) {
if (!(/^(34|37).*$/).test(attributes.creditCardNumber)) return null;
return {
presence: {message: "is required when using AMEX"},
length: {is: 5}
};
}
};
Then used as such:
validate({creditCardNumber: "4"}, constraints);
// => {"creditCardNumber": ["Credit card number is the wrong length (should be 16 characters)"]}
validate({creditCardNumber: "9999999999999999"}, constraints);
// => {"creditCardNumber": ["9999999999999999 is not a valid credit card number"]}
validate({creditCardNumber: "4242424242424242"}, constraints);
// => undefined
validate({creditCardNumber: "340000000000000"}, constraints);
// => {"creditCardZip": ["Credit card zip is required when using AMEX"]}
You could also hook those validate() functions to your component with something along the lines of @blur=validate(...)
Solution 3
Currently there are not many choices. Take a look at vue-awesome where you can find the most relevant libraries. There are 2 at the moment.
Solution 4
If you are using semantic-ui or its an option for you they have an amazing form validation plugin.
I've used it with Vuejs and it works great.
![Tiago Matos](https://lh6.googleusercontent.com/-OkHTA1a0G7A/AAAAAAAAAAI/AAAAAAAAAG0/XVesP_qQE58/photo.jpg?sz=256)
Tiago Matos
Updated on July 09, 2022Comments
-
Tiago Matos almost 2 years
Since vue-validator https://github.com/vuejs/vue-validator is being ready for Vuejs 2, what is the best way to implement frontend validation?
UPDATE I've found this awesome plugin Vee Validate