I'm constructing a form with an input field for a username. I want to restrict the username to a pretty small range of characters using regex, changing the color of the text from red to green based on the validity of the input compared to the regex as the user types.
So far it isn't picking up any characters that aren't valid despite positive testing of the regex.
https://regex101.com/r/XPFy6c/1/
/^[A-Z0-9 -]+$/igm
Here's the code, with a JSFiddle here.
const form = document.querySelector('form');
const input = document.querySelector('input');
const check = /^[A-Z0-9 -]+$/ig;
form.addEventListener("input", e => {
const checkName = check.test(input.value);
if(!check) {
input.classList.add('invalid-name');
input.classList.remove('valid-name');
} else {
input.classList.add('valid-name');
input.classList.remove('invalid-name');
}
})
.invalid-name {
color: red;
}
.valid-name {
color: green;
}
<form id="form">
<input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>
Update: Although this question is solved, if you try the code you will notice that there remains an issue with the regex alternating true/false. The solution to this problem is here.