express-form icon indicating copy to clipboard operation
express-form copied to clipboard

Support custom validators for non-required fields

Open kevinoid opened this issue 12 years ago • 3 comments

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

kevinoid avatar Dec 06 '13 20:12 kevinoid

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
  }
  ...
}

nanoamp avatar Apr 08 '14 09:04 nanoamp

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.

kevinoid avatar Apr 08 '14 12:04 kevinoid

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.

nanoamp avatar Apr 08 '14 15:04 nanoamp