pr0cz pr0cz - 1 month ago 6
CSS Question

Input element pattern regular expression does not work

I want the field to change to green, as it matches 4 letters followed by 4 numbers, like "blab1111".

This is the regex code:

[A-Za-z]{4}+[0-9]{4}
.

I tried also
^[A-Za-z]{4}+[0-9]{4}$
.

I am using this code:



input:invalid {
background: hsla(0, 90%, 70%, 1);
}

input:valid {
background: hsla(100, 90%, 70%, 1);
}

<input type='text' required name='username' autocomplete="off" id='username' pattern="[A-Za-z]{4}+[0-9]{4}" maxlength="50" />





The field is not correctly switching to the
:valid
state.

Answer

The + is too much on your regex. Use the following regex: [A-Za-z]{4}[0-9]{4} or [A-Za-z]{4}\d{4}

input:invalid {
  background: hsla(0, 90%, 70%, 1);
}
input:valid {
  background: hsla(100, 90%, 70%, 1);
}
<input type='text' pattern="[A-Za-z]{4}[0-9]{4}" required name='username' autocomplete="off" id='username' maxlength="50" />

<!-- shorter regex -->
<input type='text' pattern="[A-Za-z]{4}\d{4}" required name='username' autocomplete="off" id='username' maxlength="50" />