Yasser Shaikh
Yasser Shaikh

Reputation: 47794

Backbone.js validation get list of properties from model for which the validation has failed

I want to get a list of all model's properties that have failed validation.

For example say my model is as the one below

var OfferModel = Backbone.Model.extend({
    , defaults: function () {
        return {
            Name: '',
            FunnyUrl: "",
            StartDate: "",
            EndDate: ""
        };
    }
    , validation: {
        Name: { required: true, msg: "Name is required." },
        FunnyUrl: [{ required: true, msg: "Funny Url is required." },
                   { pattern: 'url', msg: 'Enter valid URL, eg : http://yassershaikh.com'}],        
        StartDate: { required: true, fn: 'validateStartDate' },
        EndDate: { required: false, fn: 'validateEndDate' }
    }
});

My model contains too many properties I have kept only few to explain my problem better.

So say in my model if Name and FunnyUrl are not filled, I want a list of these properties name like

I wanted the list of properties name that failed validation.

Please advice.

Upvotes: 1

Views: 238

Answers (1)

Yasser Shaikh
Yasser Shaikh

Reputation: 47794

Got it!!!! Here's the code I am using, hope this will help someone too :)

var attributes = this.model.validate(this.model.attribute);
var propertyNames = [];
_.each(attributes, function (validationMessage, propertyName) {
    propertyNames.push(propertyName);
});
console.log(propertyNames); 

Upvotes: 1

Related Questions