javascript 文本框值只允许使用 ng-pattern 的小数和数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31981153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:42:14  来源:igfitidea点击:

Textbox value to allow only decimals and numbers using ng-pattern?

javascriptangularjsregex

提问by Aravind E

In my code I need to allow decimals and integers. How can I check this using ng-pattern?

在我的代码中,我需要允许小数和整数。我如何使用ng-pattern?

example code

示例代码

my test cases

我的测试用例

1)22 = pass,

1)22 = 通过,

2)22.5 = pass,

2)22.5 = 通过,

3)2a = fail,

3)2a = 失败,

4)@#@ = fail

4)@#@ = 失败

回答by Joe Lloyd

ng-patterntakes a string.

ng-pattern需要一个字符串。

The string is regex so give this a shot

字符串是正则表达式所以试一试

/^[0-9]+([,.][0-9]+)?$/;

It allows decimal and whole numbers.

它允许小数和整数。

To check it works properly I pasted it into this

为了检查它是否正常工作,我将其粘贴到此

You can also use it to check any modifications you would like to add.

您还可以使用它来检查要添加的任何修改。

Also as Tushar said you could have this

同样正如 Tushar 所说,你可以拥有这个

/^\d+([,.]\d+)?$/;

since \d is the same as [0-9] in regex.

因为 \d 与正则表达式中的 [0-9] 相同。

回答by Shagun1390

This is also allows decimal and whole numbers.

这也允许小数和整数。

/^[0-9]+\.?[0-9]*$/