Vuejs 2 + form validation [closed] Vuejs 2 + form validation [closed] vue.js vue.js

Vuejs 2 + form validation [closed]


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.


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);// => undefinedvalidate({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(...)


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.