0

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!

1 Answer 1

1

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I've been stuck on this for days. I got so caught up with trying to get the two negated ranges to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.