freewil / express-form

Form validation and data filtering for Express
MIT License
89 stars 21 forks source link

Support custom validators for non-required fields #8

Open kevinoid opened 10 years ago

kevinoid commented 10 years ago

The fact that errors for non-required fields are ignored can really limit the utility of custom validators. It would be great if express-form could either integrate some mechanism for custom validators on non-required fields or non-field-specific/multi-field validation.

The particular use case that I have in mind is to be able to check for conditionally required fields. For example, field2 is required if field1 is provided (or if field1 has a particular value). I didn't see a way to implement this sort of logic in the current design and it would be very useful for me at the moment.

Thanks for considering, Kevin

nanoamp commented 10 years ago

It's probably a bit late now, but there's a response to another issue - https://github.com/freewil/express-form/issues/2 - which provides a possible solution by using something like

form.field('field2').custom(function(value, source) {
  if (source.field1 != undefined ) {
    // do stuff
  }
  ...
}
kevinoid commented 10 years ago

Unfortunately, that solution only works if field2 has a value. Otherwise any error returned from the // do stuff block would be ignored.

The issue here is that custom validation is ignored when non-required fields don't have a value. I only brought up the conditional-dependency as a motivating example for why such functionality could be useful. Sorry if that was confusing.

nanoamp commented 10 years ago

Ah, now I see what you mean. You're welcome to try the fork I've been working on today, to which I've added a .validateCustomIfEmpty() method. I'll probably pull-request it to here when our changes are stable.