Skip to content
Related Articles
Open in App
Not now

Related Articles

Backbone.js validationError Model

Improve Article
Save Article
  • Last Updated : 13 Jul, 2022
Improve Article
Save Article

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=
            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.

HTML




<!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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!