用于年龄验证的正则表达式,仅使用 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

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

Regex for age validation that accepts an age between 0-200 using Javascript only

javascriptregex

提问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 ifstatement 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}/;

Regex demo and explanation.

正则表达式演示和解释。

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 ifcondition without need for regex, as:

您可以简单地检查if条件而无需正则表达式,如:

if( input >=0 && input <= 200 ) {
    //its valid
}