Reputation: 820
I am writing a RegEx to use on input fields. The purpose of this is letting user enter only digits and nothing else (even dot and comma are disallowed). Here is my code so far:
RegExp = new RegExp(/^[0-9]$/);
This however still lets the user type in dots and commas. Which change I should make to get only digits?
Upvotes: 0
Views: 528
Reputation: 639
I think this might be what you need:
[Test]
public void TestRegExDigitsOnly()
{
var regEx = new Regex("^[0-9]*$");
regEx.IsMatch("123").ShouldBeTrue();
regEx.IsMatch("12.").ShouldBeFalse();
regEx.IsMatch("1.3").ShouldBeFalse();
regEx.IsMatch("abc").ShouldBeFalse();
}
Upvotes: 0
Reputation: 38094
You can use type = "number"
to allow only digits and onkeypress
event to filter dot
sign for your input
control:
<input type="number"
(onkeypress)="return (event.charCode == 8 || event.charCode == 0 ||
event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">
elements of type number are used to let the user enter a number. They include built-in validation to reject non-numerical entries. The browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by simply tapping with a fingertip.
Upvotes: 1