Backbone.js validationError Model
Backbone.js validationError Model is returned valid by the validate during the last failed validation. It is used to display an error, in case validation fails and it triggers the invalid event.
Syntax:
model.validationError
Property: It does not take any property.
Example 1: In this example, we will illustrate the Backbone.js validationError Model. Here we will print all the errors with the help of validationError.
HTML
<!DOCTYPE html> < html > < head > < title >Model Example</ title > < script src = "https://code.jquery.com/jquery-2.1.3.min.js" type = "text/javascript" ></ script > < script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type = "text/javascript" ></ script > < script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type = "text/javascript" ></ script > </ head > < body > < script type = "text/javascript" > var Person = Backbone.Model.extend({ validate: function (attributes) { var error = []; if (!attributes.name) { error.push('Empty Name!!!'); } if (attributes.age < 25 ) { error.push('Age restriction!!! '); } return error; }, }); var person = new Person(); person.set({ age: '20' }, { validate: true }); console.log(person.validationError) </script> </ body > </ html > |
Output:
Example 2: In this example, we will use validate our attributes of the model if attributes are wrong then return an error.
HTML
<!DOCTYPE html> < html > < head > < title >Model Example</ title > < script src = "https://code.jquery.com/jquery-2.1.3.min.js" type = "text/javascript" ></ script > < script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type = "text/javascript" ></ script > < script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type = "text/javascript" ></ script > </ head > < body > < script type = "text/javascript" > var Geek = Backbone.Model.extend({ initialize: function () { this.on('invalid', function (model, error) { document.write(error.join('< br >')); }); }, validate: function (attributes) { var error = []; if (!attributes.name) { error.push('Empty Name!!!'); } if (attributes.id < 0 || attributes.id > 1000) { error.push('Invalid id!!! '); } return error; }, }); var geek1 = new Geek(); geek1.set({ id: 1200 }, { validate: true }); </ script > </ body > </ html > |
Output:
Reference: https://backbonejs.org/#Model-validationError
Contact Us