The required attribute in HTML5 is very handy:
<input type="text" required>
But it still allows users to enter white space only. Is there an HTML-only solution to this?
If you want to prevent the text from wrapping, you can apply white-space: nowrap; Notice in HTML code example at the top of this article, there are actually two line breaks, one before the line of text and one after, which allow the text to be on its own line (in the code).
Use the pattern
attribute combined with the required
attribute. And be sure to include a title
attribute as well, since most browsers insert the title text into the validation pop-up bubble.
<input required pattern=".*\S+.*" title="This field is required">
The .*\S+.*
pattern requires at least one non-whitespace character, but also allows whitespace characters (spaces, tabs, carriage returns, etc.) at the beginning or end. If you don't want the user to be able to put whitespace at the beginning/end, then use this instead:
<input required pattern="\S(.*\S)?" title="This field is required">
Try the pattern
attribute. You'll need a regex which specifies 'at least one character'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With