2012-05-26 66 views
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; 
} 

檢查完全失敗,什麼是讓THR ough。我做錯了什麼,我如何使它工作?我沒有從調試器獲得任何信息。

回答

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

正則表達式Explantion

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

希望這有助於

+1

謝謝你,不知何故它的工作。 – Johanna

+0

@JohannaLindh:不客氣。 – Cylian