Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 719
BenMorel Avatar asked Dec 07 '12 15:12

BenMorel


People also ask

How can we stop white space?

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).


2 Answers

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"> 
like image 86
James Messinger Avatar answered Sep 19 '22 13:09

James Messinger


Try the pattern attribute. You'll need a regex which specifies 'at least one character'.

like image 45
robertc Avatar answered Sep 18 '22 13:09

robertc