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

38,466

Solution 1

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">

Solution 2

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

Solution 3

You probably want this:

<input type="text" required pattern="\S(.*\S)?">

(At least one non-whitespace character and no whitespace at the beginning or end of the input)


Or if whitespace at the beginning and end are fine, then this:

<input type="text" required pattern=".*\S.*">
Share:
38,466

Related videos on Youtube

BenMorel
Author by

BenMorel

Author of Brick, a collection of open-source libraries for PHP applications: brick/math : an arbitrary-precision arithmetic library brick/money : a money and currency library brick/date-time : a date and time library brick/phonenumber : a phone number library brick/geo : a GIS geometry library brick/varexporter : a powerful alternative to var_export() ... and a few others.

Updated on February 16, 2022

Comments

  • BenMorel
    BenMorel over 2 years

    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?

  • Konstantin Nikitin
    Konstantin Nikitin over 9 years
    If you don't want the user to be able to put whitespace at the beginning/end, then use this instead No, it disallowes all of the whitecharacters. Required parrern is "\S.*\S".
  • eggyal
    eggyal about 9 years
    @KonstantinNikitin: ..and that in turn requires at least two characters. If a single non-whitespace character is also valid, you'll want "\S(.*\S)?".
  • LiberalArtist
    LiberalArtist about 7 years
    You probably want \S to disallow all whitespace
  • Alex78191
    Alex78191 over 2 years
    but i can paste space