Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript validate each single character onChange or onKeyPress

I have an input field. I need the input to have the following format: AC-123456789

  • First character can either be A or B in uppercase
  • Second character can be any uppercase letter or number
  • There has to be a hyphen after the second character
  • After the hyphen there can be any number of characters between 1 and 9

I would like for the check to happen onKeyPress (in React). So if the first character is not right it will return an alerto of some kind. If the second character is not correct then I get another error. So on.

Right now my regex looks like this: /^[A,B][A-Z0-9]-\d{1,9}$/.test(value)

But this only checks once the whole input is the correct format and not after each single character is inputed in the field.

like image 205
Alpa Chino Avatar asked Oct 23 '25 02:10

Alpa Chino


1 Answers

For this specific regex, you could add a "mask", ie: your string + the end of a string you know is valid and then check if your regex passes:

const isValidString = (input) => {
  if(!input.length) return false;
  const validStr = "AC-123456789";
  const maskedStr = input + validStr.slice(input.length);
  return /^[A,B][A-Z0-9]-\d{1,9}$/.test(maskedStr);
}

console.log(isValidString("AX-12")); // true
console.log(isValidString("AX-12Z")); // false
console.log(isValidString("AX-123456789")); // true
console.log(isValidString("AX-1234567891")); // false
like image 141
Nick Parsons Avatar answered Oct 25 '25 17:10

Nick Parsons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!