javascripthtmljqueryregex

How to solve JS Regex not working during keypress


I have some requirement as below:

  1. Minimum character is 3 and maximum is 8.
  2. Only accept Capital Letter and Underscore.
  3. The 1st three (3) characters must be Uppercase.

Example acceptable input: "SAL", "SAL_", "SAL_G"

The problem now:

  1. How to control user must enter compulsory fill 1st three character with Uppercase?
  2. The underscore is not appear when press at the keyboard

enter image description here

Code

$('#myInput').on("keypress", function(e) {
  var regex = new RegExp("^[A-Z]+(?:_[A-Z]+)*$")
  var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
  if (regex.test(str)) {
    return true;
  } else {
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" type="text" id="myInput" minlength="3" maxlength="8">


Solution

  • Here I have used input event basically if you used keypress then it will not works with other touch keyboards.

    Also keypress not supports to copy pasted content also check here.

    const inputElements = document.querySelectorAll("#myInput");
    inputElements.forEach((inputElement) => {
      inputElement.addEventListener("input", function (event) {
        let inputText = event.target.value;
        let pregExpr = /[^A-Z]/g;
        if (inputText.length > 3) {
          pregExpr = /[^a-zA-Z]/g;
        }
        let sanitizedText = inputText.replace(pregExpr, "");
        if (sanitizedText.length > 2) {
          var trimmedString = sanitizedText.substring(0, 3);
          sanitizedText = trimmedString + "_" + sanitizedText.slice(3);
        }
        event.target.value = sanitizedText;
      });
    
      inputElement.addEventListener("keydown", (event) => {
        if (event.key === "Backspace") {
          let inputText = inputElement.value;
          if (inputText.endsWith("_")) {
            let newText = inputText.substring(0, inputText.length - 2);
            inputElement.value = newText;
          } else if (inputText.length > 0) {
            let newText = inputText.substring(0, inputText.length - 1);
            inputElement.value = newText;
          }
          event.preventDefault();
        }
      });
    });
    <input class="form-control" type="text" id="myInput" minlength="3" maxlength="8">

    OLD CODE VERSION

    const inputElements = document.querySelectorAll("#myInput");
    inputElements.forEach((inputElement) => {
      inputElement.addEventListener("input", function (event) {
        const inputText = event.target.value;
        let pregExpr = /[^A-Z]/g;
        if (inputText.length > 3) {
          pregExpr = /[^a-zA-Z]/g;
        }
        let sanitizedText = inputText.replace(pregExpr, "");
        if (sanitizedText.length > 2) {
          var trimmedString = sanitizedText.substring(0, 3);
          sanitizedText = trimmedString + "_" + sanitizedText.slice(3);
        }
        event.target.value = sanitizedText;
      });
    });
    <input class="form-control" type="text" id="myInput" minlength="3" maxlength="8">