We can use the regex test
method to check if the inputted string is alphanumeric.
For instance, if we have the following input:
<input>
We can check if what we typed in is alphanumeric by writing:
const input = document.querySelector('input');
input.addEventListener('change', (e) => {
if (/^[a-z0-9]+$/i.test(e.target.value)) {
console.log('is alphanumeric')
}
})
We get the input element with document.querySelector
.
Then we listen to the change
event by calling addEventListener
.
And in the event handler callback, we get the inputted value with e.target.value
.
We call test
on the /^[a-z0–9]+$/i
, which is the pattern to check if a string is alphanumeric.
If it’s alphanumeric, then ‘is alphanumeric’ is logged.