I have an input field called exampleInput. I want the user only can write these two:
var pattern = /[A-Za-z][0-9]{7}[A-Za-z0-9]/;
var pattern2 = /^[XYZ][0-9]{7}[TRWAGMYFPDXBNJZSQVHLCKE]$/i;
If they try to write a number or a string which does not match the patterns, stop the character from being shown. How can Ido that?
You need to break it down into multiple patterns and check all possible states.
Your first pattern has no start or end, not sure if that's what you want?
In my example I'll go with pattern = /^[A-Za-z][0-9]{7}[A-Za-z0-9]$/
We can check for first letter and numbers in p0 = /^[A-Za-z][0-9]{0,7}$/
And then we have it all set, if value does not follow p0 nor pattern, block it.
You can surely do more advanced regex but readability drops fast.
document.getElementById('exampleInput').addEventListener('keydown', (e) => {
if (["Backspace","Delete","Enter","ArrowLeft","ArrowRight"].indexOf(e.key) >= 0) { return; }
var value = e.target.value.substring(0, e.target.selectionStart) + e.key + e.target.value.substring(e.target.selectionEnd);
var pattern = /^[A-Za-z][0-9]{7}[A-Za-z0-9]$/;
var p0 = /^[A-Za-z][0-9]{0,7}$/
if (!p0.test(value) && !pattern.test(value)) {
e.preventDefault();
}
})
<input id="exampleInput">