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,265
  • 14
  • 27
Jackal
  • 2,979
  • 3
  • 20
  • 59
  • 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

2 Answers2

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();
  }
});

https://jsbin.com/nepuzohese/3/edit?html,js,console,output

Kieran Devlin
  • 1,265
  • 14
  • 27
  • 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
  • 12,071
  • 2
  • 35
  • 45