Jack
Jack

Reputation: 10613

Backbone.js Model validate method

How can I validate only certain attributes on a model? Currently I check if the attribute exists in the object passed into validate:

validate: function(attrs) {

        // Number
        if (attrs.minimum) {
          if (isNaN(attrs.minimum)) {
            return -1;
          }
        }
        if (attrs.maximum) {
          if (isNaN(attrs.maximum)) {
            return -1;
          }
        }
}

but if I want to validate string value then:

if (attrs.mystring) {
 // Do validation
}

would fail and the validation never takes place.

Upvotes: 0

Views: 2004

Answers (2)

Isa Ugurchiev
Isa Ugurchiev

Reputation: 74

Backbone now supports the has property. So you can do something like that:

    var Person = Backbone.Model.extend({
        defaults: {
            "name": "Kevin",
            "age" : 26,
            "job" : "web"
        },

        validate: function(attrs, options) {
            for(k in attrs) {
                if(!this.has(k)) {
                    return  k + ' attribute is not exist';
                }
            }
        }
    });

    var person = new Person;

    person.on("invalid", function(model, error) {
        console.log(error);
    });

Upvotes: 1

raddrick
raddrick

Reputation: 4453

Im a little confused by your wording, but I think you want to check if its not an empty string first? and also work out the possibility that it is undefined..if so then this is what you'll want to do..

validate: function(attrs) {
    // Number
    if (attrs.minimum) {
      if (isNaN(attrs.minimum)) {
        return -1;
      }
    }
    if (attrs.maximum) {
      if (isNaN(attrs.maximum)) {
        return -1;
      }
    }
    if (typeof(attrs.mystring) != "undefined"){
      if (!attrs.mystring){
        return -1;
      }
    }
}

if you want to only validate one of your attributes, you should write your validate function to accommodate the options accordingly

validate: function(attrs, option) {
  if (!option){
    // Number
    if (attrs.minimum) {
      if (isNaN(attrs.minimum)) {
        return -1;
      }
    }
    if (attrs.maximum) {
      if (isNaN(attrs.maximum)) {
        return -1;
      }
    }
    if (!attrs.mystring){
      return -1;
    }
  }else{
    switch(option){
      case("string"):
        if (!attrs.mystring){
          return -1;
        }
      break;
      case("number"):
        // Number
        if (attrs.minimum) {
          if (isNaN(attrs.minimum)) {
            return -1;
          }
        }
        if (attrs.maximum) {
          if (isNaN(attrs.maximum)) {
            return -1;
          }
        }
      break;
    }
  }
}

there are many ways to do this, this probably being the least efficient lol but using your example, it will do the job.

also, this isn't really a backbone.js problem per say...but general js

Upvotes: 0

Related Questions