Skip to content

Added Key( obj ) Assert #18

Open
Elzair wants to merge 1 commit intoguillaumepotier:masterfrom
Elzair:master
Open

Added Key( obj ) Assert #18
Elzair wants to merge 1 commit intoguillaumepotier:masterfrom
Elzair:master

Conversation

@Elzair
Copy link

@Elzair Elzair commented Aug 5, 2014

This new Assert determines if a given string or property name is a key in another object. I needed a way to create a constraint where the value of a given key was itself a key in another object.

Here is the sample code:

  var carriers = JSON.parse(yield fs.readFile(__dirname + '/../conf/sms_carriers.json', 'utf8'));

  // Validate input
  var validator = new valid.Validator();
  var constraint = {
      from:    new valid.Assert().Email()
    , to:      new valid.Assert().Regexp(/^\d+$/)
    , carrier: new valid.Assert().Key(carriers)
    , subject: new valid.Assert().NotBlank()
    , text:    new valid.Assert().NotBlank()
  };
  var options = yield parse(this);
  var validated = validator.validate(options, constraint);
  if (!validated) {
    for (var err in validated) {
      if (validated.hasOwnProperty(err)) {
        this.body += util.format('Invalid %s', err);
      }
    }
    return;
  }

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 this pull request may close these issues.

1 participant