This article explains Model Validation in Backbone with jQuery. Here we will create a simple form and use validation when the form information is filled in that displays the validation message.
We will now create the sample application showing the use of validation.
Now add the HTML page.
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Form validation using backbone jquery</title>
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.1.1/lodash.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js'></script>
<script>
jQuery(function($) {
//Backbone Model and Validation Method
var Client = Backbone.Model.extend({
// RegEx Patterns
// ==============
patterns: {
specialCharacters: "[^a-zA-Z 0-9]+",
digits: "[0-9]",
email: "^[a-zA-Z0-9._-]+@[a-zA-Z0-9][a-zA-Z0-9.-]*[.]{1}[a-zA-Z]{2,6}$",
phone: "^([0-9]{3})?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"
},
// Validators
// ==========
validators: {
minLength: function(value, minLength) {
return value.length >= minLength;
},
maxLength: function(value, maxLength) {
return value.length <= maxLength;
},
pattern: function(value, pattern) {
return new RegExp(pattern, "gi").test(value) ? true : false;
},
isEmail: function(value) {
return Client.prototype.validators.pattern(value, Client.prototype.patterns.email);
},
isPhone: function(value) {
return Client.prototype.validators.pattern(value, Client.prototype.patterns.phone);
},
hasSpecialCharacter: function(value) {
return Client.prototype.validators.pattern(value, Client.prototype.patterns.specialCharacters);
},
hasDigit: function(value) {
return Client.prototype.validators.pattern(value, Client.prototype.patterns.digits);
}
},
validate: function(attribute) {
console.log('attribute', attribute);
var errors = this.errors = {};
if (attribute.fname != null) {
if (!attribute.fname) errors.fname = 'First Name of Person is Required';
else if (!this.validators.minLength(attribute.fname, 2)) errors.fname = 'Length of First Name is too Short';
else if (!this.validators.maxLength(attribute.fname, 15)) errors.firstname = 'Length of First Name is too large';
else if (this.validators.hasSpecialCharacter(attribute.fname)) errors.fname = 'It does not contain special characters';
}
if (attribute.lname != null) {
if (!attribute.lname) errors.lname = 'Last Name of Person is Required';
else if (!this.validators.minLength(attribute.lname, 2)) errors.lname = 'Length of Last Name is too Short';
else if (!this.validators.maxLength(attribute.lname, 15)) errors.lname = 'Length of Last Name is too Large';
else if (this.validators.hasSpecialCharacter(attribute.lname)) errors.lname = 'It does not contain special characters';
}
if (attribute.password != null) {
if (!attribute.password) errors.password = 'Required Password';
else if (!this.validators.minLength(attribute.password, 6)) errors.password = 'Length of Password is too short';
else if (!this.validators.maxLength(attribute.password, 15)) errors.password = 'Length of Password is too Large';
else if (!this.validators.hasSpecialCharacter(attribute.password)) errors.password = 'password must contain a special character';
else if (!this.validators.hasDigit(attribute.password)) errors.password = 'password must contain a digit';
}
if (attribute.email != null) {
if (!attribute.email) errors.email = 'Email is required';
else if (!this.validators.isEmail(attribute.email)) errors.email = 'Mail Format is not valid';
}
if (attribute.phone != null) {
if (!attribute.phone) errors.phone = 'Phone Number is required';
else if (!this.validators.isPhone(attribute.phone)) errors.phone = 'Invlaid Phone Number';
}
if (!_.isEmpty(errors)) {
return errors;
}
}
});
var Record = Backbone.View.extend({
events: {blur: 'validate'},
initialize: function() {
this.name = this.$el.attr('name');
this.$msg = $('[data-msg=' + this.name + ']');
},
validate: function() {
var self = this,
obj = {};
obj[this.name] = this.$el.val();
this.model.set(obj, {validate: true, validateAll: false}, { error: function(model, obj) {
console.log(obj);
}}
);
this.$msg.text(this.model.errors[this.name] || '');
}
});
//Create the Model Instance
var client = new Client;
$('input').each(function() {
new Record({el: this, model: client});
});
});
</script>
</head>
<!--create an HTML Form-->
<body>
<form>
<label>First Name</label>
<input type="text" name='fname'>
<span data-msg='fname'></span>
<br>
<label>Last Name</label>
<input type="text" name='lname'>
<span data-msg='lname'></span>
<br>
<label>Password</label>
<input type="password" name='password'>
<span data-msg='password'></span>
<br>
<label>Email</label>
<input type="text" name='email'>
<span data-msg='email'></span>
<br>
<label>Phone</label>
<input type="text" name='phone'>
<span data-msg='phone'></span>
</form>
</body>
</html>
Provide something in the text boxes. It will then display the validation message as in the following: