1

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 ?

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
Justin
  • 21
  • 4
  • 1
    `onkeypress` triggers BEFORE the text has changed. Try `oninput` instead. – Poul Bak Oct 22 '22 at 10:27
  • 1
    Inline event handlers like `onkeypress` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. The [`keypress` event](//developer.mozilla.org/en/docs/Web/API/Element/keypress_event) itself is deprecated, so yes, use the [`input` event](//developer.mozilla.org/en/docs/Web/API/Element/input_event)! – Sebastian Simon Oct 22 '22 at 10:32

1 Answers1

1

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>
Debug Diva
  • 26,058
  • 13
  • 70
  • 123