I have this HTML field:
<input type="text" name="userInput" id="userInput">
I want to make sure that the user enters either at least five characters or nothing at all.
This code, which only tests for the minimum five characters is working fine:
userInputValue = $("#userInput").val();
if (/^([A-Za-z]{5,})/.test(userInputValue) === false) {
alert("More than five, please!");
return false;
}
However, when I try to add a condition to skip this check if the field is blank, either like this
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;
}
}
or like this
userInputValue = $("#userInput").val();
if (/^([A-Za-z]{5,})/.test(userInputValue) === false && userInputValue !== "") {
alert("Either more than five or none at all, please!");
return false;
}
the check fails completely and anything is let through. What am I doing wrong and how do I make it work? I’m not getting any info from the debugger.
Just changed a bit, adding a
?right place.RegEx Explantion
Hope this helps