Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validating complex attribute as a whole #261

Closed
juodaspaulius opened this issue Jan 21, 2015 · 4 comments · Fixed by #264
Closed

Validating complex attribute as a whole #261

juodaspaulius opened this issue Jan 21, 2015 · 4 comments · Fixed by #264

Comments

@juodaspaulius
Copy link

Lets say the model has attribute which value is complex object such as:

complex : { 
    one: "val1",
    two: ""
}

Currently, due to flattening, this attribute can only be validated using validation keys complex.one and complex.two, but not on a whole object complex. What I would really like to do is to specify custom validator on complex, for example like this:

validation: {
    complex: function(val){
          if (val && val.one && val.two){
               return "Only one of values allowed";
          }
    }
}

To make it work I minorly modified flatten function to include the key of complex object in addition to other flattened nested keys.
My modified flatten function is:

var flatten = function (obj, into, prefix) {
    into = into || {};
    prefix = prefix || '';

    _.each(obj, function(val, key) {
        if(obj.hasOwnProperty(key)) {
            if (val && typeof val === 'object' && !(
                val instanceof Array ||
                val instanceof Date ||
                val instanceof RegExp ||
                val instanceof Backbone.Model ||
                val instanceof Backbone.Collection)
            ) {
                flatten(val, into, prefix + key + '.');
            }
            // Removed this else statement so that the key of the complex is always added as well
            // else {
                into[prefix + key] = val;
            // }
        }
    });

What do you think, perhaps it could be included into the upstream?

@blikblum
Copy link
Contributor

I like the idea, this will allow to validate also properties in the middle of the obj path

@platinumazure
Copy link

Great idea! If no one else wants to, I wouldn't mind writing a pull request and tests for this feature.

@chiefGui
Copy link
Collaborator

@platinumazure please, do it.

@blikblum
Copy link
Contributor

I suggest to merge #260 first to avoid conflicts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants