32 mins ago
32 mins ago

Reputation: 75

JavaScript real-time validation

I have a website for mobile subscribers, and i want the field where they enter their phone numbers to accept only "numbers" and the numbers should be only 7 digits, no more, no less. So if they try to input non-integer sign it'll be auto removed/will not even show up... How to achieve that?

Upvotes: 0

Views: 839

Answers (1)

Delan Azabani
Delan Azabani

Reputation: 81412

Well, for limiting the length of the input, use the maxlength attribute to the input element.

To only allow numeric characters, bind a JavaScript event handler to the keypress event, and preventDefault from the event object to drop the key if it isn't a number.

Edit:

Do some testing to make sure other commonly-used keycodes are allowed in addition to number character keys, such as arrow keys, delete and backspace. If the user can't do these, it'll certainly be a problem.

There are other ways to approach this. You could, for example, avoid the trouble of allowing other special keys, by filtering and deleting non-numeric characters entered each time a key is pressed, which should be invisible and instant seeing as the maximum number of characters is 7.

Edit 2:

If this seems reasonable for you, HTML5 introduces a number of native form validation features that may help, and are supported by fairly recent versions (and newer) of most browsers. This is great to also cover those who don't have JavaScript enabled (but, remember, always do server-side validation as well).

Upvotes: 1

Related Questions