简体   繁体   English

正则表达式仅允许和仅允许数字

[英]RegEx to allow only and only digits

I am writing a RegEx to use on input fields. 我正在编写要在输入字段上使用的RegEx。 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? 我应该做出哪些更改才能只获得数字?

You can use type = "number" to allow only digits and onkeypress event to filter dot sign for your input control: 您可以使用type = "number"来仅允许数字和onkeypress事件来过滤input控件的dot号:

<input type="number"
   (onkeypress)="return (event.charCode == 8 || event.charCode == 0 || 
   event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">

As MDN says: 正如MDN所说:

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. 浏览器可能会选择提供步进箭头,以使用户可以使用他们的鼠标或通过简单地用指尖点击来增加和减少该值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM