I have a if statement that checks if the user left the input empty and did not enter the correct pattern (which is essentially a student number). However, it seems when I input a random mash of words and number, it still passes, as if it is not checking the regex validation.
var idInput = formHandle.f__id; //this connects back to my HTML form
var studentNum = /(n|N)d{8}/;
if (idInput.value === "" && !studentNum.test(idInput)) {
idInput.style.background = 'red';
idInput.focus();
return false;
}
2
Answers
&&
should be an||
: If the input is empty or doesn’t match the regex. Since the regex won’t match an empty string, you don’t need theidInput.value === ""
check though.!studentNum.test(idInput)
should be!studentNum.test(idInput.value)
^
(start of string) and$
(end of string) in the regex. Without them, this just searches for "n or N followed by 8 digits" anywhere in the string.Fixed code:
(side note, is there any reason to use
var
instead oflet
/const
?)I would have just left this as a comment, but I don’t have enough reputation.
Based on your question, I believe your code simply has a logic error.
As far as I can tell, you want to enter the if statement in the case that the input is invalid (so it is empty, or violates the regex). However, you are using
&&
instead of||
.For your test case, if you enter random characters, then
idInput.value !== ""
, so the if statement will not be executed.