bee
bee

Reputation: 1623

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 other than a string in this format.

However, I am having no luck. The example of my code is located here

Upvotes: 0

Views: 56

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

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:

<input type="text" name="code" pattern="a[0-9]{6}" required
               title="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<input type="text" name="code" pattern="[0-9]{6}" required
                                     title="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.

Upvotes: 1

Related Questions