我正在制作一个联系人表单,该表单将与jQuery一起提交,我只需要进行一个简单的验证。
我需要验证一个字段,它必须至少有x个整数。
我该怎么做?
附言:请不要建议使用验证插件。
谢谢,
编辑:这是我试过的,但我想是错的。
var numbercheck = /^(wd{7,14})?$/;
这是jsdiffle:
http://jsfiddle.net/4WqY9/
使用regex
提供您在领域中可以承受的数字范围
如d{5,10} // Here 5 -10 is the range of numbers
function testContact(contact){
contact = contact.replace(/[a-z]*/g,"");
return (contact == contact.match(/d{5,10}/))?true:false;
}
要使用正则表达式匹配多个整数,您需要以下内容:
^((d*)s*)*$
我会写一个小函数来完成这项工作。注意,如果inputText
:-中有任何非int元素,则此函数将返回false
function HasRequiredIntegers(inputText, requiredIntegers) {
var elems = inputText.split(/s+/);
var intCount = 0;
var nonIntCount = 0;
for (i = 0; i < elems.length; i++) {
if (((parseFloat(elems[i]) == parseInt(elems[i])) && !isNaN(elems[i]))) {
intCount++;
}
else {
nonIntCount++;
}
}
return (intCount >= requiredIntegers && nonIntCount == 0);
}
试试这个
function hasUpTo5(strin){
if( string.replace(/[^0-9]/g, '').length <= 5){
return true
}else{
return false;
}
}
alert( hasUpTo5("fhsfbgurb3utn55nun44") );