Question

Could you explain why Validator.js starts the way it does(see first code snippet) and why I'm not able to call the prototyped method validate (second snippet)

I'm currently playing with validator.js (github/validator.js)

the code begins like this:

    ( function ( exports ) {

var Validator = function ( options ) {
this.__class__ = 'Validator';
this.__version__ = '@@version';
this.options = options || {};
this.bindingKey = this.options.bindingKey || '_validatorjsConstraint';

return this;
};

Validator.prototype = {

constructor: Validator,

validate: function ( objectOrString, AssertsOrConstraintOrGroup, group ) {
  if ( 'string' !== typeof objectOrString && 'object' !== typeof objectOrString )
    throw new Error( 'You must validate an object or a string' );
......

Yet I'm NOT ABLE to call the validate method in my node.js code which is as follows:

var Validator = require('./static/vendor/parsley/validator.js'),
Assert = Validator.Assert,
Constraint = Validator.Constraint;

Validator.Validator().validate( 'foo', new Assert().Length( { min: 4 } ) );

Thank you, Baradi

Was it helpful?

Solution

To create an instance (that will inherit from the prototype), you will need to use the new keyword:

new Validator.Validator().validate( 'foo', new Assert().Length( { min: 4 } ) );

Also, from a constructor you don't need to return this. That would've hinted at the mistake as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top