Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form input realtime feedback

Tags:

javascript

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.

like image 592
Andy Avatar asked Feb 28 '26 08:02

Andy


1 Answers

if you only care about modern browsers, you don't even need JavaScript!

input { border: 2px solid #DDD; }
input:invalid { border-color: red; }
input:valid { border-color: green; }
<input type="text" pattern="^[A-Z0-9 -]{1,12}$">
like image 165
FiniteLooper Avatar answered Mar 02 '26 22:03

FiniteLooper



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!