Open In App

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.






<!DOCTYPE html>
<html>
  
<head>
    <title>Model Example</title>
    <script src=
            type="text/javascript"></script>
  
    <script src=
        type="text/javascript"></script>
  
    <script src=
        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:

Backbone.js validationError Model

Example 2: In this example, we will use validate our attributes of the model if attributes are wrong then return an error.




<!DOCTYPE html>
<html>
  
<head>
    <title>Model Example</title>
    <script src=
            type="text/javascript"></script>
  
    <script src=
        type="text/javascript"></script>
  
    <script src=
        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:

Backbone.js validationError Model

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


Article Tags :