Reputation: 3
I'm having trouble trying to get JavaScript and Regex to recognize an input from an HTML file that I'm working on.
function validateSchoolClass(field)
{
if(field == "")
{
return "No class ID was entered.\n";
}
else if (field.length != 4)
{
return "Class ID must be 4 characters.\n";
}
else if (/[^A-Z]{2}[^0-9]{2}/.test(field))
{
return "Class Name must be two capital letters followed by two numbers.\n";
}
return "";
}
What I want to happen is that input into the field that is passed will contain 4 characters the first 2 will be capital letters and the next 2 will be numbers. I don't know if I'm missing something but from everything that I have read this should work, but it doesn't and any 4 character input that is passed still counts as being valid!
Upvotes: 0
Views: 59
Reputation: 1073968
I'd change that final else if
to
else if (!/^[A-Z]{2}[0-9]{2}$/.test(field))
That regular expression tests for two capital letters followed by two digits, and then I use the !
to invert the result, so you can report things that don't match. (I also added anchors at the beginning and end, but with your earlier length check, they're probably technically superfluous.)
Upvotes: 1