使用ng-pattern的正则表达式仅用于数字(无空格或特殊字符) [英] Regex for numbers only (no spaces or special chars) using ng-pattern
问题描述
我有一个输入字段,仅当它只包含数字,没有特殊字符且没有空格时才有效.我在Angular中使用ng-pattern来验证输入.
I have an input field that should only be valid if it contains only digits and no special characters and no spaces. I am using ng-pattern in angular to validate the input.
我尝试使用:
/^\d+$/
/^\d*$/
/^[0-9]+$/
这些操作可防止出现特殊字符和字母,但对空格不执行任何操作.有谁知道将空格视为无效字符的正则表达式?我试图避免阻止使用keyCode进行输入.
These work to prevent special characters and letters, but do nothing about the spaces. Does anyone know a regex that would consider spaces an invalid character? I am trying to avoid preventing the input using keyCode.
很抱歉是否已经有这个话题.我发现了很多类似的东西,但是没有任何帮助.
I apologize if there's already a thread for this. I found many similar ones but nothing that helped with the spaces.
即使正则表达式被认为可以正常防止空格,它似乎也无法与ng-pattern一起使用:
Even if the regex is supposed to prevent spaces normally, it is does not seem to be working with ng-pattern:
<input type="tel" maxlength="10" ng-pattern="/^[0-9]+$/" placeholder="(1234567890)" />
如果我输入空格,仍在输入上返回 ng-valid-pattern
类.
Is still returning the ng-valid-pattern
class on the input if I type a space.
推荐答案
此模式应起作用:/^ \ d + $/
This pattern should work: /^\d+$/
这篇关于使用ng-pattern的正则表达式仅用于数字(无空格或特殊字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!