Aessandro
Aessandro

Reputation: 5771

Backbone validation

The validation works correctly but something is not right:

var User = Backbone.Model.extend({
validate: function(attr, options){
    var errors = [];
    if(attr.age < 18){
        errors.push('too young');
    }
    if(attr.firstname === ''){
        errors.push('name required');
    }
    if(errors.length === 0){}
    else{
        return errors;
    }
},
urlRoot: '/users'
});

If I remove the following: "if(errors.length === 0){}", even if the validation is correct (in that case invalid shouldn't be called), "user.save doesn't" doesn't seem to work:

saveUser: function (ev){
    var userDeatils = $(ev.currentTarget).serializeObject();
    var user = new User({validate:true});
    user.on("invalid", function(model, error) {
        if(error[0]){
            errorAge(error[0]);
        }
        if(error[1]){
            inputRequired(error[1]);
        }
    });
    user.save(userDeatils,{
        success: function(user){
            router.navigate('', {trigger:true});
        }
    })
    return false;
},

full code here (for showing code only)

Upvotes: 0

Views: 188

Answers (1)

Vitalii Petrychuk
Vitalii Petrychuk

Reputation: 14255

I would suggest to follow this pattern https://gist.github.com/addyosmani/3516103

Your example is buggy because first name can have either 0 or 1 index and in case it has 0 index you show age error with the text of the name error :)

Upvotes: 1

Related Questions