Skip to content Skip to sidebar Skip to footer

Regular Expressions: Jquery Check

I am working on a form text input that requires the user to enter an 'a' followed by 6 proceeding numbers (0-9). (a|)\d{6} The JS does not allow the user to type in anything ot

Solution 1:

It is a very bad idea to stop the user from typing anything they want. Here's why:

Let's say I miss the key I intended to press, and end up entering this sequence of keystrokes:

a123rBackspace456

I would expect that my slip would have been erased by my backspace, and the rest of the input went through. Imagine how surprised I'd be to see "a12456" in there instead, because your code had already stopped me from typing r, which means that my Backspace erased the 3!

Instead, try this:

<inputtype="text"name="code"pattern="a[0-9]{6}"requiredtitle="Please enter an &quot;a&quot; followed by six digits." />

Demo on JSFiddle

This feature of HTML5 will prevent the form from being submitted if the user does not enter data in the correct format. This, combined with server-side confirmation, will work beautifully. Plus, it even works if the user has JavaScript disabled!

That said, for such a specific format, it may be more helpful to do this:

a<inputtype="text"name="code"pattern="[0-9]{6}"requiredtitle="Please enter six digits" />

Demo on JSFiddle

In this way, the "a" is already there and doesn't have to be typed, leaving the user to only need to type the part that changes. On the server, just stick the "a" back on to it.

Post a Comment for "Regular Expressions: Jquery Check"