使用两个条件验证输入字段

时间:2012-05-26 12:19:35

标签: javascript jquery regex validation

我有这个HTML字段:

<input type="text" name="userInput" id="userInput">

我想确保用户输入至少五个字符完全没有

此代码仅测试最少五个字符,但工作正常:

userInputValue = $("#userInput").val();
if (/^([A-Za-z]{5,})/.test(userInputValue) === false) {
    alert("More than five, please!");
    return false;
}

但是,当我尝试添加条件以跳过此检查时,如果该字段为空,则可以像这样

userInputValue = $("#userInput").val();
if (userInputValue !== "") {
    if (/^([A-Za-z]{5,})/.test(userInputValue) === false) {
        alert("Either more than five or none at all, please!");
        return false;
    }
}

或者像这样

userInputValue = $("#userInput").val();
if (/^([A-Za-z]{5,})/.test(userInputValue) === false && userInputValue !== "") {
    alert("Either more than five or none at all, please!");
    return false;
}

检查完全失败,任何事情都可以通过。我做错了什么,我该怎么做?我没有收到调试器的任何信息。

1 个答案:

答案 0 :(得分:1)

稍微改了一下,添加?正确的位置。

userInputValue = $("#userInput").val();
if (userInputValue !== "") {
    if (/^([A-Za-z]{5,})?$/.test(userInputValue) === false) {
        alert("Either more than five or none at all, please!");
        return false;
    }
}

RegEx说明

"^" +              // Assert position at the beginning of a line (at beginning of the string or after a line break character)
"(" +              // Match the regular expression below and capture its match into backreference number 1
   "[A-Za-z]" +       // Match a single character present in the list below
                         // A character in the range between “A” and “Z”
                         // A character in the range between “a” and “z”
      "{5,}" +           // Between 5 and unlimited times, as many times as possible, giving back as needed (greedy)
")?" +             // Between zero and one times, as many times as possible, giving back as needed (greedy)
"$"                // Assert position at the end of a line (at the end of the string or before a line break character)

希望这有帮助