Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Pattern - regex not working

Tags:

html

regex

I'm trying the pattern attribute for the first time, and I can't get it to work (my browser does support it, though).

Right now I have:

input type="text" pattern="[a-zA-Z0-9]{6}" name="formName"

The first problem is that is doesn't notify me if it's blank; the second problem is that if I do type in something, it won't accept it. I want it to accept alphanumeric characters and be exactly 6 characters is length. I tried it with forward slashes and a few other variations.

like image 327
John Smith Avatar asked May 14 '13 12:05

John Smith


Video Answer


1 Answers

As Duikboot already pointed out, the right way to do it is:

<input type="text" name="formField" pattern="[a-zA-Z0-9]{6}" required>

The required attribute causes the validation to fail, when the field is empty.
The pattern attribute defines the regex to test against, when the field is not empty.
(Your initial pattern seems to work fine.)

More info can be found here.
This is simple enough so as not to require a demo, but nonetheless you can find one here.

like image 74
gkalpak Avatar answered Nov 01 '22 03:11

gkalpak