简体   繁体   中英

Backbone validation return attribute name

In model:

 validation: {
        title: {
            required: true
        },
        body: {
            required: true
        }
    }

In view I call:

this.parent.model.isValid(['title', 'body']);

This only return my true/false, how to change validation to get parameters names which are not valid ?

I can't pass atributtes one by one, because It can be a lot.

It's explained in docs mate

Failed validations trigger an "invalid" event, and set the validationError property on the model with the value returned by this method.

var Chapter = Backbone.Model.extend({
  validate: function(attrs, options) {
    if (attrs.end < attrs.start) {
      return "can't end before it starts";
    }
  }
});

var one = new Chapter({
  title : "Chapter One: The Beginning"
});

one.on("invalid", function(model, error) {
  alert(model.get("title") + " " + error);
});

In your case (code not tested, I hope you get the idea):

this.parent.model. = Backbone.Model.extend({
      validate: function(attrs, options) {
        var errors= new Array;
        if (!attrs.title) {
          errors.push("Title is required");
        }
        if (!attrs.body) {
          errors.push("Body is required");          
        }
        if errors.length
            return errors;
      }
    });

this.parent.model.on("invalid", function(model, error) {
      alert(error);
    });


//You don't need to pass an attribute list
this.parent.model.isValid();

Note you'll keep the errors array (if any) at this.parent.model.validationError for later processing so you don't need to capture the "invalid" event on the model

Overwrite the validate function http://backbonejs.org/#Model-validate

perform wtv filter you want and return wtv object you want.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM