Backbone.js isValid() Model

The Backbone.js isValid() Model is a function that is used to check the state of the model in Backbone.js. It uses validate method to check the model. It checks validation for each attribute. 

Syntax: 

model.isValid( options );

Properties:

  • options: It is the options that which is passed to validate the method.

Example 1: In this example, we will illustrate isValid() function. We will use isValid() function without defining validate function.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS isValid Model</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.2.2/backbone-min.js"
        type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        w3wiki
    </h1>
    <h3>BackboneJS isValid Model</h3>
    <script type="text/javascript">
        var Person = Backbone.Model.extend();
        var person = new Person();
        document.write('You mode state is  ',
            person.isValid());
    </script>
</body>
  
</html>


Output:

Backbone.js isValid method

Example 2: In this example, we will use isValid() function and verify the age and non-emptiness of the name in model.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS isValid Model</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.2.2/backbone-min.js"
        type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        w3wiki
    </h1>
  
    <h3>BackboneJS isValid Model</h3>
      
    <script type="text/javascript">
        var Person = Backbone.Model.extend({
            validate: function (attributes, options) {
                document.write("You data is validating...<br>");
                if (!attributes.name) {
                    return ('Please enter the name!!!<br>');
                }
  
                if (attributes.age < 25) {
                    return ('You are age below required!!! ');
                }
            },
        });
        var person = new Person({ name: "hello", age: 20 });
        if (person.isValid()) document.write("You all data is valid");
        else document.write(person.validationError);
    </script>
</body>
  
</html>


Output:

Backbone.js isValid Model

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