50

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?

BenMorel
  • 34,448
  • 50
  • 182
  • 322

4 Answers4

106

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">
kano
  • 5,626
  • 3
  • 33
  • 48
James Messinger
  • 3,223
  • 3
  • 25
  • 16
  • 9
    _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"`. – Konstantin Nikitin Mar 06 '15 at 11:21
  • 10
    @KonstantinNikitin: ..and that in turn requires at least two characters. If a single non-whitespace character is also valid, you'll want `"\S(.*\S)?"`. – eggyal May 02 '15 at 01:32
14

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

Community
  • 1
  • 1
robertc
  • 74,533
  • 18
  • 193
  • 177
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.*">
Jeremy Moritz
  • 13,864
  • 7
  • 39
  • 43
0

step 1

create a Javascript function:

function ignoreSpaces(event) {
  var character = event ? event.which : window.event.keyCode;
    if (character == 32) return false;
}

Step 2

use it on any text-input field in HTML.

<input type="text" id="userInput" onkeypress="return ignoreSpaces(event)">

Working example :

index.html

<html> 
<body>
  <input type="text" onkeypress="return ignoreSpaces(event)">
  
  <script>
    function ignoreSpaces(event) {
        var character = event ? event.which : window.event.keyCode;
        if (character == 32) return false;
    }
  </script>

</body>
</html>
S007
  • 61
  • 4