I have this input
[DataType(DataType.Password)]
public int Pin
<input asp-for="Pin" Pattern="[1-9]+" />
yet it still lets me type letters
I have this input
[DataType(DataType.Password)]
public int Pin
<input asp-for="Pin" Pattern="[1-9]+" />
yet it still lets me type letters
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" />
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
.
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.