Lion789
Lion789

Reputation: 4482

Validation in Backbone is not validating?

Hey so I know backbone changed there validation and I am trying to make it work? Anyone notice what went wrong. Here is the JSfiddle link that validates as well. Do not understand why is not validating. http://jsfiddle.net/NcHTb/

Code:

(function () {
    window.App = {
        Models: {},
        Collections: {},
        Views: {},
        Templates: {},
        Router: {}

    };


    App.Models.User = Backbone.Model.extend({
        defaults: {
            firstName: 'first',
            lastName: 'last',
            email: 'Email',
            phone: '222',
            birthday: 'date'
        },

        validate: function (attrs) {
            if (!attrs.firstName) {
                return 'You must enter a real first name.';
            }
            if (!attrs.lastName) {
                return 'You must enter a real last name.';
            }
            if (attrs.email.length < 5) {
                return 'You must enter a real email.';
            }
            if (attrs.phone.length < 10 && attrs.phone === int) {
                return 'You must enter a real phone number, if you did please remove the dash and spaces.';
            }
            if (attrs.city.length < 2) {
                return 'You must enter a real city.';
            }
        }

    });


    var user = new App.Models.User();
    //user.on('change', function () {
    //  console.log('something changed'); - used for change anything
    //});
    user.on('invalid', function (model, invalid) {
        console.log(invalid);
    });
    user.on('change:firstName', function () {
        console.log('something changed');
    });

    user.set('firstName', '');
    console.log(JSON.stringify(user));
    console.log(user.get('birthday'));






})();

Upvotes: 1

Views: 127

Answers (1)

gustavohenke
gustavohenke

Reputation: 41440

As already answered by @nikoshr, the problem has been resolved in this question.

You basically have to pass { validate: true } as the options of your call to set(). The save() method always trigger the validation.
In the end, your code will be like this:

user.set('firstName', '', { validate: true }); // Run validations
user.set('firstName', '');                     // Doesn't run validations
user.save();                                   // Run validations

Upvotes: 5

Related Questions