用于年龄验证的正则表达式,仅使用 Javascript 接受 0-200 之间的年龄
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29467075/
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
Regex for age validation that accepts an age between 0-200 using Javascript only
提问by Vg.
I want a regex that allows users to enter only numbers between 0 and 200. I've tried this but it doesn't work:
我想要一个正则表达式,它允许用户只输入 0 到 200 之间的数字。我试过这个,但它不起作用:
var age_regex=/^\S[0-9]{0,3}$/;
采纳答案by Pramod Karandikar
Instead of regex, you can compare numerical value itself:
您可以比较数值本身,而不是正则表达式:
var ageValue = 50; // get the input age here
var ageNumericVal = +ageValue;
if (ageNumericVal < 0 || ageNumericVal > 200) {
// invalid
}
回答by Rahul Desai
I strongly recommend using an if
statement for this since regex is not efficient for this case.
我强烈建议if
为此使用一个语句,因为正则表达式在这种情况下效率不高。
Anyway, if you really want to use RegEx, try the following:
无论如何,如果您真的想使用 RegEx,请尝试以下操作:
var age_regex=/\s[0-1]{1}[0-9]{0,2}/;
EDIT:
编辑:
Using this regex in <input>
:
使用这个正则表达式<input>
:
(Working Demo)
(工作演示)
p{
color: red;
}
<form action="#">
Enter Age: <input type="text" name="number" pattern="[0-1]{1}[0-9]{0,2}" title="Please enter a valid number between 0 and 200.">
<input type="submit">
</form>
<p>This form will give error if number does not pass the regex.</p>
回答by Rahul Tripathi
You can try this:
你可以试试这个:
^(0?[1-9]|[1-9][0-9]|[1][1-9][1-9]|200)$
An easy fix to check age would be not to use regex and simply check like this:
检查年龄的一个简单方法是不使用正则表达式,只需像这样检查:
if(age >= 0 && age <= 200)
{
//code
}
回答by Sudhir Bastakoti
you could simply check in if
condition without need for regex, as:
您可以简单地检查if
条件而无需正则表达式,如:
if( input >=0 && input <= 200 ) {
//its valid
}