guillaumepotier / validator.js

Powerful objects and strings validation in javascript for Node and the browser
http://validatorjs.org
MIT License
255 stars 39 forks source link

Strict check for constraints #2

Closed nateevans closed 11 years ago

nateevans commented 11 years ago

I think it would be helpful to have a strict mode for Constraint. (If there is already something to this effect in validator, please correct me)

If the Constraint key does not exist in the object to be validated, a Violation should occur. Maybe should be tied to the Required assertion.

var obj = {
    a: 'foo',
    b: 'bar'
};

var constraint = {
    a: new Assert().Required(),
    b: new Assert().Required(),
    c: new Assert().Required()
};

// obj.c == undefined but constraint.c == Assert().Required(). Violation should occur.
var violations = Validator.validate( obj, constraint );

I would attempt to do this myself, but my JavaScript Fu is not as strong as yours.

Thanks!

nateevans commented 11 years ago

PS: I know I could check for the keys outside of Validator... but why not let Validator do the validating :)

nateevans commented 11 years ago

Modifying the Constraint.check() to this gets part of the way there...

    check: function ( object, group ) {
      var result, failures = {};

      for ( var property in this.nodes ) {
//        if ( this.has( property ) ) {
          result = this._check( property, object[ property ], group );

          // check returned an array of Violations or an object mapping Violations
          if ( ( _isArray( result ) && result.length > 0 ) || ( !_isArray( result ) && !_isEmptyObject( result ) ) )
            failures[ property ] = result;
//        }
      }

      return failures;
    }

But the Violation.__toString() doesn't return a very useful message anymore.

Based on the example above:

> violations.c[0].__toString();
   "Required assert failed for "undefinedundefined"

It would be helpful to have the original missing property name in the violation message.

guillaumepotier commented 11 years ago

To be sure I'm well understanding this case.

Currently, if you define validators for prop that are not existing, they are failing (what we could consider as a strict mode). You'd like to be able to ignore these errors in a not strict mode ?

guillaumepotier commented 11 years ago

Oh and btw, thanks for using validator.js :)

guillaumepotier commented 11 years ago

Done, + doc here: http://validatorjs.org/#constraint-definition

Hope that helps you. Great idea.

nateevans commented 11 years ago

Awesome. works pretty nicely! thanks