tgriesser / checkit

simple, flexible validations for node and the browser
MIT License
223 stars 53 forks source link

null and '' get a pass? #75

Open cdscott opened 8 years ago

cdscott commented 8 years ago

The section below seems a bit odd to me as. If I have optional email field for users validated with 'email' rule, they can submit null and '' as values and it passes. However if they provide ' ' (single space) it fails as an invalid email. This seems like a bit of a hole for all rules (except 'accepted', 'exists', and 'required'). If I don't want to require an email, but want it validated if present, I would NOT expect '' or null to pass validation. Null and '' ARE values to be validated against. Thoughts?

// If the rule isn't an existence / required check, return // true if the value doesn't exist. if (rule !== 'accepted' && rule !== 'exists' && rule !== 'required') { if (value === '' || value == null) return; }

joepie91 commented 7 years ago

I would say that this makes some sense in the contexts where checkit might be used; namely:

Because of these usecases, both null and an empty string could be considered to be "non-existent", and therefore when optionally accepting an e-mail address, it'd be sensible to ignore (and pass) null and empty strings.

If you want stricter validation - for example, because you're building a JSON API - then you might be looking for exists instead of required, which only verifies that the field isn't undefined. See also my reference here.

EDIT: More specifically answering your question, I don't think there's currently a way to modify what counts as "existence" in optional scenarios. Perhaps there should be.