1

I have a form with standard text elements:

<form id="f">
    <input type="text" name="from" pattern="^[A-Za-z ]+$>
    <input type="text" name="to"   pattern="^[A-Za-z ]+$>
</form>

And I'd like to prevent users from entering disallowed characters into them. For example, typing 0 should have no effect.

How can I do this?

Zaz
  • 46,476
  • 14
  • 84
  • 101

1 Answers1

1
$("#f input[type=text]").keypress( function(e) {
    new_text = $(this).val() + String.fromCharCode(e.which)
    pattern = $(this).attr("pattern")
    return Boolean(new_text.match(pattern))
})

The code works by returning false, and thereby cancelling the keypress, if the new text does not match pattern. It's important to use function(e) instead of (e) => because the latter would bind this lexically, whereas we want to let jQuery bind this to the respective input element.

Zaz
  • 46,476
  • 14
  • 84
  • 101