CodesJava

Easy learning with example program codes

Backbone.JS Validate()


The Backbone.JS Validate() model is used to validate the input before displaying the result. For invalid inputs, the Backbone.JS Validate() model returns specified error message and for the valid inputs, it just display the result.

Syntax:

Model.Validate (attributes, options)   

Parameters:
attributes: This parameter is used to specify the properties of a model.
options: This parameter is used to specify the options like id, name etc. for a model.

Example:

<!DOCTYPE html> 
<html>
<head>  
<title>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 X = Backbone.Model.extend({  
defaults: {  
student_name: 'Tom',  
student_age: 10,  
},  
initialize : function(){  
this.on("invalid",function(model,error){  
document.write(error);  
});  
},  
validate: function(attributes) {  
if ( attributes.student_age < 10 ) {  
return 'Enter the correct age.';  
}  
},  
});  
var Y = new X();  
Y.on('invalid', function() {  
this.arguments;  
});  
Y.set({ student_age : '9' }, { validate : true });  
</script>  
</body>  
</html>

Output:

Enter the correct age.

Explanation:
Since we set the value of student_age less than 10, hence it returned a Validation Error message.

Please follow and like us:


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki