Is it possible to configure a required field to ignore white space?

BenMorel picture BenMorel · Dec 7, 2012 · Viewed 34.6k times · Source

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?

Answer

James Messinger picture James Messinger · Jun 26, 2013

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+" title="This field is required">