validator.js icon indicating copy to clipboard operation
validator.js copied to clipboard

Added Key( obj ) Assert

Open Elzair opened this issue 11 years ago • 0 comments

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;
  }

Elzair avatar Aug 05 '14 21:08 Elzair