aurelia / validatejs

Enables expressive validation using decorators and/or a fluent API.
MIT License
22 stars 23 forks source link

Validator.validate returns nothing #61

Closed ggrimbert closed 8 years ago

ggrimbert commented 8 years ago

Hi,

I am integrating your validators methods inside my app, and I just come to find something weird :

In the method Validate (Validator.js)

 validate(prop) {
    let config = metadata.getOrCreateOwn(validationMetadataKey, ValidationConfig, this.object);
    let reporter = ValidationEngine.getValidationReporter(this.object);
    if (prop) {
      config.validate(this.object, reporter, prop);
    } else {
      config.validate(this.object, reporter);
    }
  }

You make a call to config.validate, which returns the errors, but you never return the call to this method, so the validate never returns anything.

(validation-config.js)

 validate(instance, reporter, key) {
    let errors = [];
    this.__validationRules__.forEach(rule => {
      if (!key || key === rule.key) {
        let result = rule.rule.validate(instance, rule.key);
        if (result) {
          errors.push(result);
        }
      }
    });
    reporter.publish(errors);
    return errors;
  }

In my case, I want the validation on "save" button click, and if the result of the validation is OK, then I save.

So, am I supposed to put my save code inside the reporter.subscribe method, or set a variable in this method (in the case this call is synchronous), or am I missing something ?

ggrimbert commented 8 years ago

Another weird thing, validateJs can have options, one of them is 'fullMessages', that permits to not show the name of the field in the error message, but I can't make it work. I believe this is due to

var result = (0, _validate3.default)(target, validator);  (validation-rule.js)

but the function called here needs 3 parameters.

apawsey commented 8 years ago

Most people's approach at the moment is to call validate, and in the subscribe call back, set the returned errors to a local variable that you can then check. I agree that it should return the errors, and so much so that I put exactly that behaviour in my refactoring test PR, which I unfortunately still need to sort out though. (not great with git/github)

apawsey commented 8 years ago

In order to send the options, you can pass the config into either the fluent or decorators parameters.

For example... new Validator(this).ensure('firstname').required({message:'^Fill it in dummy'}); will replace the default validatejs message with "Fill it in dummy" (note the ^, stops validate js from prepending the property name).

ggrimbert commented 8 years ago

Thanks for the tip with the ^, this works perfectly.

plwalters commented 8 years ago

The validate method doesn't return the results, they are reported via the reporter. The readme shows an example.