Open In App

Backbone.js validate() Model

The Backbone.js validate Model is validation logic that we want to apply for all the attributes of model. If the attributes are valid, don’t return anything from validate, If they are invalid return an error message. It can be as simple as a string error message to be displayed, or a complete error object that describes the error. 

Syntax:



model.validate( attributes, options );

Parameters:

Example 1: In this example, we will illustrate the Backbone.js validate Model. In this example we will see validate will trigger when we set the value of the model with the help of the set method. 






<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS validate Model</title>
        type="text/javascript">
    </script>
    <script src=
        type="text/javascript">
    </script>
    <script src=
        type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <h3>BackboneJS validate Model with set</h3>
    <script type="text/javascript">
        var Person = Backbone.Model.extend({
            validate: function (attributes) {
                document.write("You data is validating...<br>");
                if (!attributes.name) {
                    document.write('Please enter the name!!!<br>');
                }
  
                if (attributes.age < 25) {
                    document.write('You are age below required!!! ');
                }
            },
        });
        var person = new Person();
        person.set({ name: "hello", age: '23' }, { validate: true });
    </script>
</body>
  
</html>

Output:

Backbone.js Validate model

Example 2: In this example, we will trigger validate function when saving function of the model is called.




<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS validate Model</title>
        type="text/javascript">
    </script>
    <script src=
        type="text/javascript">
    </script>
    <script src=
        type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <h3>BackboneJS validate Model with save</h3>
    <script type="text/javascript">
        var Person = Backbone.Model.extend({
            validate: function (attributes) {
                document.write("You data is validating...<br>");
                if (!attributes.name) {
                    document.write('Please enter the name!!!<br>');
                }
                if (attributes.age < 25) {
                    document.write('You are age below required!!! ');
                }
            },
        });
        var person = new Person();
        person.save({ age: '25' });
    </script>
</body>
  
</html>

Output:

Backbone.js Validate Model

Reference: https://backbonejs.org/#Model-validate


Article Tags :