Reputation: 31
I'm new to regex and facing issue in below problem statement.
Problem statement : What I need is a text box where the content must start with 2 upper case alphabets and follows by 3 digits. This textbox can be empty.
function validateModuleCode()
{
var m = document.getElementById("moduleCode").value;
if (/^[A-Z]{2}[0-9]{3}$/.test(m) == false)
{
document.getElementById("moduleError").innerHTML = "Invalid";
return false;
}
else
{
document.getElementById("moduleError").innerHTML = "";
return true;
}
}
Module Code:
<br/>
<input type = "text" id = "moduleCode" name = "module code" onkeypress = "validateModuleCode()">
<span style = "color:red" id = "moduleError"></span>
<br/><br/>
However, the moduleError
keeps popping out and shows invalid even though I have entered a valid value. Here is the error image.
How do I correct this ?
Upvotes: 1
Views: 155
Reputation: 27232
You can use oninput
event to get the updated input value. Also, You have to add a check for the empty value. So that it should be valid if there is no value in the text box.
Live Demo :
function validateModuleCode() {
var m = document.getElementById("moduleCode").value;
if (m && (/^[A-Z]{2}[0-9]{3}$/.test(m) === false)) {
document.getElementById("moduleError").innerHTML = "Invalid";
return false;
} else {
document.getElementById("moduleError").innerHTML = "";
return true;
}
}
<input type="text" id="moduleCode" name="module code" oninput="validateModuleCode()">
<span style="color:red" id="moduleError"></span>
Upvotes: 1