Search code examples
javascriptregexvalidationwhitelist

Smart whitelisting for a value restricted input


I need to restrict an input so that the user can only enter dollar amounts. This means that they can enter a string of digits, optionally followed by a decimal and 0-2 more digits. No commas, no dollar signs.

I found what I think is a good pattern for this, but I also want to allow the user to use backspace, enter, tab, etc. I was hoping for a better way to do this than explicitly listing every valid keycode on my whitelist. I was hoping that /\W/ would do the trick, but alas, it matches too many keypresses.

This is what I currently have.

  $input.keypress(function(evt) {
    var ch = String.fromCharCode(evt.which);
    var val = evt.target.value + ch;
    var pattern = /^\d+(\.?(\d{1,2})?)$/;
    if (!pattern.test(val)) {
      evt.preventDefault();
    }
  });

If there's a smart and clean way to allow the user to make corrections and to navigate the form with the keyboard, I'd be glad to hear it.

If you have a suggestion for improving the Regex above, please feel free to include that in your answer (or leave it in a comment if you don't have an answer).

Thanks!


Solution

  • When I do this in my code, I don't run the regex on the keypress itself but on the contents of the field they are typing into. That way you don't need to worry about non-printing characters. You will need to worry about them cut-n-pasting into the field which will not fire that keypress event too.