checkit icon indicating copy to clipboard operation
checkit copied to clipboard

null and '' get a pass?

Open cdscott opened this issue 7 years ago • 1 comments

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

cdscott avatar Sep 16 '16 13:09 cdscott

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

  • HTML forms sent over HTTP (where empty inputs might show up as an empty string), and other "untyped" encodings
  • Libraries that return either a value or null if there is no value to be returned

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.

joepie91 avatar Jan 19 '17 12:01 joepie91