1

I have this input

 [DataType(DataType.Password)]
 public int Pin

<input asp-for="Pin" Pattern="[1-9]+" />

yet it still lets me type letters

Kieran Devlin
  • 1,373
  • 1
  • 12
  • 28
Jackal
  • 3,359
  • 4
  • 33
  • 78
  • Your question relates to HTML rather than .NET. – Kieran Devlin Jul 02 '19 at 19:15
  • 3
    Possible duplicate of [HTML5: number input type that takes only integers?](https://stackoverflow.com/questions/8808590/html5-number-input-type-that-takes-only-integers) – austin wernli Jul 02 '19 at 19:16
  • Possible duplicate of [Make Input Type="Password" Use Number Pad on Mobile Devices](https://stackoverflow.com/questions/19126856/make-input-type-password-use-number-pad-on-mobile-devices) – Peter Wolf Jul 02 '19 at 19:17
  • Well as far as i know i'm setting it as password type using an annotation tho – Jackal Jul 02 '19 at 19:17
  • I wouldn't bother blocking non-numbers. If the user types in the wrong value that it their problem. – Intervalia Jul 02 '19 at 20:29

3 Answers3

2

I personally would just use the password input field and then use JavaScript to block all non numerical input from being added.

Here's an example:

document
  .getElementById("numeric_input")
  .addEventListener("keypress", function(evt)
  {
      if (evt.which < 48 || evt.which > 57)
      {
        evt.preventDefault();
      }
  });
<input type="text" id="numeric_input" />
Kieran Devlin
  • 1,373
  • 1
  • 12
  • 28
  • I wouldn't even block non-numbers. If the user types in the wrong value that it their problem. – Intervalia Jul 02 '19 at 20:28
  • Thanks this is probably the way to go about it – Jackal Jul 02 '19 at 20:31
  • @Intervalia It depends on the use case, I find that if you can validate something then you should as it will ultimately result in a better user experience even if the user notices it or not. – Kieran Devlin Jul 02 '19 at 22:01
  • Be aware that this code will prevent backspace, arrows and other special keys. Best to improve the `if` statement to not disallow those keys. – Intervalia Jul 02 '19 at 22:33
  • @Intervalia https://stackoverflow.com/questions/5597060/detecting-arrow-key-presses-in-javascript It would appear different browsers behave differently. – Kieran Devlin Jul 02 '19 at 22:37
0

The pattern attribute validates the input on form submission, but doesn't enforce it while typing.

The basic HTML form validation features will cause this to produce a default error message if you try to submit the form with either no valid filled in, or a value that does not match the pattern.

rickvdbosch
  • 14,105
  • 2
  • 40
  • 53
0

While the accepted answer works correctly, it does not account for the enter key, and as such, the user is unable to use this key to submit their form. The solution that worked for me was:

if (!/^\d+$/.test(evt.key) && evt.key !== 'Enter') {
  evt.preventDefault();
}

The test function tests the input for being a numeral.

jared-wt
  • 1
  • 1