Search code examples
javascriptregexinputregex-negationregex-group

regex input only the allowed pattern (input text)


I have an input text field where I want to allow a pattern input example:

hd546648 -ok

Vg315248 - ok > 2 character what can be letter (lowercase, uppercase), and 6 character only numbers

on("input", "test", function(event) {
const invalidChars = /^[^A-Za-z]{1,2}\D{1,6}$/g;
ob = event.target;
if (invalidChars.test(ob.value)) {
  ob.value = ob.value.replace(invalidChars, "");
}
});

If I use only this /^[^A-Za-z]{1,2}/g; its working, I can type only letters to the text box, but if I add the number part, something is wrong.

What I want to do, if I type in the input box, replace any characters that is not A-Z or a-z, for first 2, and replace any other character that is not number 0-9 for 3-8. So for first 2 only enable letters and from 3 to 8 enable only numbers.


Solution

  • Using a regex on the whole thing won't work, as each validation can invalidate another part of the input. This solution checks each character in turn, and truncates to the length of the last valid character. Fiddle here: https://jsfiddle.net/spwe4k21/

    $(function() {
      $("#submit").attr("disabled", true);
    
      $("#userinput").keyup(function() {
        let input = $(this).val();
        let cleanedInput = cleanInput(input);
        $(this).val(cleanedInput);
    
      });
    });
    
    function cleanInput(input) {
      let tests = [/[a-z]/i, /[a-z]/i, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/];
      for (let i = 0; i < tests.length; i++) {
        if (input[i] == undefined || !tests[i].test(input[i])) {
          return input.substring(0, i);
        }
      }
    
      return input.substring(0, tests.length);
    }