I have an input field. I need the input to have the following format: AC-123456789
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With