Open In App

Backbone.js validationError Model

Last Updated : 13 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads