square / lgtm

Simple object validation for JavaScript.
Other
370 stars 40 forks source link

Question: why is validation response structure like it is? #11

Closed bitinn closed 9 years ago

bitinn commented 9 years ago

Just curious: it seems like we must return 1 and only 1 message for each attribute, but result for each errors attribute is an array, why?

// Validate all attributes and return results with a promise.
validator.validate(person).then(function(result) {
  console.log(result);
  // { "valid": false, "errors": { "firstName": [ ], "lastName": ["You must enter a last name."], "age": [ ] } }
});
bitinn commented 9 years ago

Got it now, looks like if you have multiple rules for an attribute, say .required follow by .using, then lgtm will run all rules on this attribute, and if both rules failed, result will contain both messages (which is kinda weird, because it means you can't gate your .using rule with a .required rule, if you are not careful, can result in runtime error on .using rule.)

bitinn commented 9 years ago

I am closing this, been using lgtm with validator for a few days, a joy to create schema-like validation :+1:

eventualbuddha commented 9 years ago

This is something that people occasionally have trouble with. The idea is that LGTM doesn't want to make assumptions about how you're going to present your error messages, so it runs all validations whose conditions are met and lets you sort out how to display them.

Is there somewhere you looked for information on this but didn't find it? I think it'd be useful to update the wiki with a clearer explanation.

bitinn commented 9 years ago

@eventualbuddha Having an example showcasing required + using chained together and what error result you may get, will make it easier to understand why lgtm response is designed that way.

Also it should probably clarify whether All validation is done asynchronously means, I think it means each rules are done async, so if you have multiple rules chained together (after a validates clause), you shouldn't expect the rule to complete in sequences (and thus error response maybe out of order), true or false?

eventualbuddha commented 9 years ago

@bitinn Thanks for the suggestions. I added a section to the wiki showing how to do chaining and changed the part mentioning asynchronous validations to explain that they could be in an unexpected order. Ideally the order would map to your calls to .using or .required, but that's not how it works right now.

bitinn commented 9 years ago

:+1: thx