1

我有这个 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;
}

检查完全失败,任何事情都可以通过。我做错了什么,我该如何让它发挥作用?我没有从调试器获得任何信息。

4

1 回答 1

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;
    }
}

正则表达式解释

"^" +              // 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)

希望这可以帮助

于 2012-05-26T12:21:55.167 回答