JavaScript - 如何验证字段以允许某些字符和特定长度

时间:2010-12-20 08:55:03

标签: javascript validation

我需要验证一个文本框,因此它的值包含10个字符(不多于,不能少于)。下面的代码完成了它,允许我分别为每个字段设置限制长度。

 function charLength(elem, min, max){
 var uInput = elem.value;
 if(uInput.length >= min && uInput.length <= max){
                alert("Invalid number of characters");
  elem.focus();
  return false;
 }else{
  return true;
 }
}

这就是我所说的:

onBlur="charLength(document.getElementById('tf1'),1,9)"

但我验证的字段不仅必须是10个字符,而且还必须以字母Z开头。

我如何进行此类验证?这首先有可能吗?

4 个答案:

答案 0 :(得分:2)

也尝试一下:

 function charZ10(elem, min, max){
 var uInput = elem.value;
     if(uInput.length >= min && uInput.length <= max && uInput.substr(0, 1) == "Z"){
          alert("Material number has to consist of 10 characters begining with Z");
          elem.focus();
        return false;
     }
     else return true; //i 
}

并尝试在文本框中添加maxlength

<input type="text" maxlength="10">

答案 1 :(得分:1)

function charZ10(elem, min, max){
    var uInput = elem.value;
    if(uInput.length == 10 && uInput.substr(0, 1) == "Z")
        return true;
    alert("Material number has to consist of 10 characters begining with Z");
    elem.focus();
    return false;
}

答案 2 :(得分:1)

function charZ10(elem) {
    var pass = /^Z.{9}$/.test(elem.value); // 10 chars starting with Z
    if (!pass) {
        alert("Try again, noob.");
        elem.focus();
    }
    return pass;
}

答案 3 :(得分:0)

必须

 if(uInput.length <= 10 && substr(uInput,0, 1) == "Z")