简体   繁体   English

如何在javascript中验证范围为5-20的数字?

[英]How to validate digits only with range 5-20 in javascript?

I tried like below 我尝试过如下

function isValidMobileNo(mobNo) {
    var pattern = /^\d{20}$/;
    return pattern.test(mobNo);
}

if (!isValidMobileNo(temp)) {
    $("#spanRegMobNo").html("Only Numbers allowed and limit is 5-20");
    return ("Only Numbers allowed and limit is 5-20" + "\n");

} else {
    $("#spanRegMobNo").html("");
    return "";
}

but here I have to enter 20 digits but where I want to give 5-20 range? 但在这里我必须输入20位数,但我想给5-20范围? so how? 又怎样?

Change your regex to 将你的正则表达式改为

var pattern = /^\d{5,20}$/;

Use range to allow from 5 to 20 digits. 使用范围允许5到20位数。


I'd also recommend to use the same regex on the input element on pattern attribute. 我还建议在pattern属性的input元素上使用相同的正则表达式。

 input:valid { color: green; } input:invalid { color: red; } 
 <input type="text" pattern="\\d{5,20}" /> 

If you use HTML, you can use the input number tag. 如果使用HTML,则可以使用输入数字标记。

<input type="number" name="quantity" min="1" max="5">

Else, in javascript, the pattern "/^\\d{5,20}$/" :) 否则,在javascript中,模式“/ ^ \\ d {5,20} $ /”:)

Your question is not clear so here is 2 solutions for 2 cases. 你的问题不明确,所以这里有两个案例的2个解决方案。

If you don't want to use regex, you can also use this method(it's also check if it's a number-or string number like: "123" ): 如果你不想使用正则表达式,你也可以使用这个方法(它还检查它是否是数字或字符串数​​字,如: "123" ):

This example will check if the number length is between 5 to 20: 此示例将检查数字长度是否介于5到20之间:

function isValidMobileNo(mobNo) {
    var numLength = mobNo.toString().length;
    return (isNaN(mobNo) && numLength >= 5 && numLength <= 20);
}

This will check if the number range is between 5 to 20: 这将检查数字范围是否在5到20之间:

function isValidMobileNo(mobNo) {
    return (isNaN(mobNo) && mobNo >= 5 && mobNo<= 20);
}

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

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