Form Validation made with Easiest JS Validator
easiest-js-validator
This library offers a simple way to validate your forms, without complicated logic. You can bind with Vue to your data object and define a rules object and then a messages one, to display them if validation fails. The easiest way to validate your forms without 3rd party packages. Also, the library is written in ES2015.
Example
Installation
npm i easiest-js-validator
App.vue
import Validator from 'easiest-js-validator'
export default {
data () {
return {
errors: {},
//form object
profile: {},
//rules object
rules: {
email: 'required,email',
last_name: 'required,alpha',
first_name: 'required,alpha'
},
//error messages
messages: {
'required': 'The field is required.',
'email': 'The field must be a valid email address.'
}
}
},
methods: {
// submit the form.
submit: function () {
// check for validation rules.
let validate = Validator.make(this.profile, this.rules, this.messages)
if (Object.keys(validate).length > 0) {
this.errors = validate
return false
}
this.errors = []
console.log('Do something amazing!')
},
// look up possibles validation errors.
hasError: function (key) {
return typeof this.errors[key] !== 'undefined'
}
}
}
A part of the form used for validation
<form class="form-horizontal" role="form" @submit.prevent="submit">
<div v-bind:class = "{ 'has-error': hasError('first_name') }">
<label class="col-sm-3 control-label">First Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" placeholder="First Name"
v-model = "profile.first_name">
<span class="help-block"
v-if = "hasError('first_name')">{{ errors.first_name }}
</span>
</div>
</div>
<button type="submit">
<i class="fa fa-paper-plane"></i>
Submit
</button>
</form>