Restricting input with jQuery

If there’s one thing that drives me insane online, it’s when input forms allow me to enter incorrect data, only to point out the mistake after I try and submit it. It seems like half the forms I submit have to be refilled and submitted over again because I didn’t include an uppercase letter in my password, or I did, or the password can only be numerical, or some other requirement nobody thought to mention.

The way the brain works, we look for solutions based on the tools in front of us. You don’t enter uppercase letters at the ATM do you? No, because the ATM keypad only has numbers. You might hit the wrong number by mistake, but you’ve never tried to enter your email address, or your mother’s maiden name.

Therein lies the problem, the keyboard that you use complicates inputting data online. It probably has between 75 and 100 keys and even more characters are easily accessible by holding multi-key combinations. Using it to log into Facebook is rather like popping out for milk in a Ferrari.

Of course, your keyboard has to have more input options than any particular form field requires, because it’s a multi-use tool; you can’t practically have a different keyboard for every possible type of input.

This leads to a serious usability issue: users are constantly being asked to ‘correct’ their information to suit a form. That’s a great way to increase frustration and lose business.

Touchscreen devices have made great strides in this area by modifying the onscreen keyboard to tailor the types of input possible, to the data required; enter an email address on an iPhone for example, and you won’t be able to enter a space by mistake, because the spacebar isn’t provided.

Digital Keyboard

Digital keyboard image via Shutterstock

Until we’re all working on touchscreens, we need a temporary solution, and there’s actually quite a simple one: using jQuery we can slip a layer of intelligence between the keyboard and the input field and only accept the data if it falls within expected bounds, ignoring anything outside those bounds, confident that it’s an error.

First, we need to set up an input field in HTML that we want to restrict, a phone number for example:

<label for="phone">Phone:</label>
<input type="text" id="phone" />

Then, in the document’s head, we need to import jQuery:

<script type="text/javascript" src=""></script>

And immediately afterwards add the following script:

<script type="text/javascript">
$(document).ready(function() {
    $('.phoneInput').keypress(function(key) {
        if(key.charCode < 48 || key.charCode > 57) return false;

This script runs once the document is ready, attaching a keypress method to the .phoneInput input field. We then detect which key has been pressed based on its charCode property — the number 0 is assigned the code 48, 1 is 49 and so forth — any key that’s outside our range should return false. If the method returns false the browser will simply ignore the keystroke.

This means that if the user hits any key that isn’t 0–9 the input will be ignored, effectively restricting the input to numbers.

We can apply the same technique to almost any field, building up complex rules using logical AND and logical OR. For example, if we wanted to restrict input for a surname, we would need to restrict input to lowercase letters (97–122), uppercase characters (65 – 90) and the occasional hyphen (45):

$('.surnameInput').keypress(function(key) {
if((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45)) return false;

You can try out a demo here.

This code is a progressive enhancement. It will take some of the strain off your server validation, but that doesn’t mean that you shouldn’t also validate information you’re gathering.

Prevention, as the saying goes, is better than cure; and using this tip you’ll see a reduction in the number of people who start, but don’t complete your forms, especially when complex data requirements are involved.

Do users regularly make mistakes on your forms? How do you handle the mistakes? Let us know in the comments.

Featured image/thumbnail: keyboard image via Shutterstock

  • Ben P Ford

    Great stuff. Just goes to show how a tiny bit of extra thought and time in development stage can make a big difference to the user.

    Just make sure to allow for the tab key, backspace key, etc.

    • Benjie

      Thanks! I wrote the article above the way I did because it was the simplest way to explain it. However in a practical implementation I’d probably suggest excluding characters rather than including them.

      So for example, instead of including alphanumerics and a few special characters for an email address field, I would test for characters I didn’t want instead (spaces for example).

      That would produce a lot more code, and be harder to read, but it has the benefit of including keys by default; so you don’t need to worry about including backspaces etc.

  • creativescreenname

    However, it also restricts use of the backspace and delete keys, which also help prevent errors.

    • Benjie

      See my reply to Jason’s comment, I’ve included the characters for deleting and tabbing.

  • Bryan Gruhlke

    I agree with your frustration with forms. With mobile websites you can use new HTML5 field attributes (like type=”num”) to show the appropriate touchscreen keyboard, but that doesn’t always translate well in desktop browsers (especially older browsers). Using jQuery or another JavaScript approach is a really simple and clean way to help users submit correct data on the first attempt. Overall, a pretty simple idea that I believe can make forms a bit more friendly. Thanks for the article!

    • Benjie

      You’re welcome :)

  • Todd Gilbert

    Shame we can’t just change the input’s type to show the proper keyboard (ala type=”email”).

    As I understand it isn’t allowed for security purposes.

    • Benjie

      Agreed! It will come eventually, and not too soon for me.

  • Jason

    Unfortunately, it also appears to break tab navigation. Once I start typing a phone number, I’m unable to tab into the next field.

    • Benjie

      Good point Jason! On some browsers (Firefox) you have a little more control than others: Webkit and IE don’t need any extra code, but for Firefox you may want to include the delete, backspace and tab keys to make sure they still work:

      if((key.charCode 57) && key.charCode != 0 && key.charCode != 8 && key.charCode != 9 && key.charCode != 46) return false;

      • AMYunus Com

        Nice. But still need more enhancements. Such as Ctrl+A for blocking
        text in the input field. And does it work to number on the right side of

  • alanhogan

    This is an absolutely terrible idea, and NOT a best practice.

    As people note below, it breaks things; and the user gains nothing; and users with macros set up (e.g. TextExpander; for me, typing “pphone” (sic) auto-expands to my phone number) will be stymied.

    Please do not foist this upon your users.

    • Benjie

      I can’t agree that restricting input on a text field breaks anything; I’ve never heard of a case where preventing someone from entering a space in a field designed to accept an email address caused any kind of problem.

      It’s true that some macros would be affected, but if you had one set up with a personal email address with the abbreviation ‘pemail’ you’d have no problem whatsoever.

      Likewise, preventing someone from accidentally entering illegal characters in a password field would not cause any problems.

      Used sparingly this is a perfectly valid technique.

  • Štěpán Ulver

    I think regexp would be better for name check. It’s really frustrating, when you can’t submit correct data, like your name, due to somebody’s restriction ;)

  • Benjie

    Alan, you’ve misunderstood what I’m advocating here.

    The example you describe involves replacing mission-critical code that belongs on the server-side with client-side JavaScript and that is not what I’ve suggested.

    As I’ve clearly stated in the article this is a progressive enhancement, only valuable in cases where a validator would catch the error in any case.

    This script will improve the usability of most online forms, provided it is used with common sense and not abused.

    That said, I would love to read your ‘failure scenario’ if you can think of one.

    • alanhogan

      I said no such thing. Read my comment again. The end result is a user may end up with a password other than that which they believed they entered.

      And this is no progressive enhancement, nor a problem that needs solving.

      As you note, server-side enforcement is always needed. Client-side validation is fine, but actively intercepting keystrokes is extremely difficult to do without unintended side-effects. Doing so in password fields, as you explicitly suggested, is a particularly nasty suggestion.

      • Benjie

        Alan, in your comment posted above you’ve given the example of a user signing up for a service and creating a password which is then altered without his/her knowledge.

        That is not what has been suggested, as you can see by reading the article.

        If you don’t want to use the technique, then don’t worry, it’s not compulsory :)

      • alanhogan

        If, as you suggest, keystrokes for disallowed characters are discarded as the user types them into a password field, then yes, in a sense, it will have been “altered without their knowledge” (unless they notice the lack of a new bullet as they type it; this is hardly guaranteed!).

        If I am missing something, kindly point it out.

      • Benjie

        What you’re missing is that if a square bracket is an illegal character in the login system (to take your example), then it will only ever be entered in error. It is, by definition, a mistake.

        There are two reasons a user could enter a square bracket in this case:

        1) They type it by mistake, in which correcting it may mean that they log in first time (assuming the rest of the characters are correct).

        2) They don’t know what their password is, in which case the bracket will be stripped, but the password mis-match will be caught by the validator.

        The only time that there could be a problem would be if a character were treated as legal at sign-up and then illegal at log-in, which would be a poor implementation.

        I wouldn’t suggest using this script for a sign-up password for the reasons I’ve indicated above. But if you did throw common sense to the wind and do so, provided you were consistent with which characters were illegal you would be unlikely to encounter a problem because the password would be modified identically during both processes.

        However, let me reiterate: I would not recommend using this script for anything other than progressive enhancement. Doing so with any JavaScript would be a mistake.

  • Jarrod

    I’ve got to say this is a bad idea, accessibility-wise. If you’re removing mistyped characters, those using assisting technologies will be entering incorrect (to them) information that will pass validation. Furthermore, regardless of accessibility concerns, you now can’t easily see where the mistyping occurred, as the mistyped character has been removed. For instance, if I inadvertently mistype my credit card number, and while looking at the keyboard type a ‘w’ instead of ‘2’ it will be much more difficult to determine where the mistype occurred

    • Benjie

      There are definitely times that you wouldn’t want to use this.

      In the case of credit card details, it would definitely be useful to prevent users entering spaces that are usually displayed on cards, but usually aren’t wanted on the backend (provided that you also make provision to strip the spaces out on the backend in case JavaScript is disabled).

  • Evan Jacobs

    Your example references a class in the selector, when you should be pointing at $(‘#phone’) – #corrections

    • Benjie

      Thanks Evan, but if you target the ID then you don’t have the option of applying it to multiple instances.

  • Dominik

    To avoid a long if-statement you could use a simple array of ‘forbidden’ codes and check if the pressed key is within this array by using jQuery:
    if($.inArray(key.charCode, myArray) < 0) {
    return false;

  • Kevin Bond

    What if the user pastes text?

  • Eduardo

    As other mention (and you tried to fix) there is a big amount of keys or shortcuts not directly related to the control, but to the browser and OS that you need to address. Maybe you will be safer with a blacklist approach. I.e. If you field is numeric, reject letters a-z and A-Z. A visual indicator that the key is being reject could be good UX also.

  • Stewart Orr

    I tried something like this a few years ago but instead of using keycodes I used regular expression to make it easier to choose what keys are allowed. It was experiemental but seems to hold up pretty well in most browsers and does help guide users to what data they should enter.

  • Eric

    In my opinion, absolutely terrible. At the very least your example should include help text. I know, they are just examples, but people reading this article may assume this is OK practice for a website. What happens if my number is international and I want to include +64 at the start? A lot of average users to not know this can be written as 0064. What if it’s a work number and I need to include ‘extension 09’ at the end?

    As for the surname example – wow! Couldn’t exclude more users if your tried! What if I don’t speak English and can only write my last name in Chinese characters? What if I have a macron or an accent? What if I’d legally changed my name to A$AP?

    I really think this article could do with a warning that these are just examples of what you can do – but I highly doubt there are many practicable examples of when this is appropriate.

    • Benjie

      Thanks for your opinion!

      We could of course type out a whole website to ensure readers don’t mistake small code snippets for a full application, hopefully most readers realize that examples are provided without any context.

      However, both examples are perfectly valid and have numerous real-world applications:

      Most businesses don’t have or want international clients. Plumbers, movie theaters, accountancy firms etc. are all localized. Those that are international have a separate field on a form for country because it carries far wider implications than just the international dialing code.

      As for surnames, you’ll find that you can enter “Wen”, “Jhang”, “Chan” or “Diao” without a problem. For any English-speaking company, only accepting communication in a recognizable form is a practical necessity; if I can only read English and you can only write Chinese, we won’t have much to say in any case.

      I wouldn’t normally advocate omitting graves, accents or umlauts etc. but if you’ve designed a site that will display the name using a highly optimized font that omits analphabetic characters (not to mention Chinese characters) to save file size then omitting the accent is preferable to omitting the character altogether.

      And if you’ve changed your name to A$AP then you have more problems than filling out a contact form.

  • Marcelo Davanzo

    Some languages other than English have surnames in which apostrophes and other special diacritic characters are common figures. Your example does not account for that and while I understand it is just an example, by restricting input like that you could be frustrating some users while pleasing others.