0

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?

1
  • How are you applying the regex? show the HTML (or more JS) Commented Aug 15, 2019 at 11:55

2 Answers 2

1

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"> 

As MDN says:

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.

Sign up to request clarification or add additional context in comments.

4 Comments

He said 'dot' is not allowed!
It does not prevent the mentioned unwanted characters.
@callback thanks for your attention. Great. I've edited a reply.
@BanafshehKhadem thanks for your attention. Cool. I've edited a reply.
0

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

1 Comment

this is allowing + character. I dont want + sign to be entered also. what should be regex in this case?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.