Sometimes, a form is required but you don’t want to enter anything. The form will not allow nothing to be entered as a valid answer:

value.length > 0

There are usually a few ways around this.

First, you may check if a simple space character is sufficient. If this is successfully submitted, then they do not trim the input. However, it is much more likely that this input is trimmed before validation:

value != null && value.trim().length > 0

Most implementations of a trim function will remove many (but not all) white space characters. The form may check that the input contains at least one non-whitespace character:

/\S/u.test(value)

This might be sufficient, as modern regular expression and JavaScript tend to be Unicode-aware, and it will cover the most common whitespace characters. However, it is still possible that there are edge-cases (such as U+0085). It may be better to explicitly check for the White_Space property for a more complete Unicode-aware solution:

/\P{White_Space}/u.test(value)

Finally, there are some remaining edge-cases to be aware of. Namely, the zero-width space (U+200B) and the Braille blank character (U+2800). These seem to work the best for submitting “empty” forms, as they are often overlooked, not normally stripped as whitespace.


See also: spaces

Back to home