Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex check a user input string in JavaScript

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;
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Your && 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 the idInput.value === "" check though.
  2. !studentNum.test(idInput) should be !studentNum.test(idInput.value)
  3. You forgot the anchors ^ (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:

var idInput = formHandle.f__id; //this connects back to my HTML form
var studentNum = /^(n|N)\d{8}$/;
if (!studentNum.test(idInput.value)) {
    idInput.style.background = 'red';
    idInput.focus();
    return false;
}

(side note, is there any reason to use var instead of let / const?)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading