1

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.

3 Answers 3

3

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" />

Sign up to request clarification or add additional context in comments.

3 Comments

Oh jeezus. Thank you very much! I tried the regex code with the "+" on the regex101.com website and they told me, it should work. Is the "+" maybe a unregulary problem on some servers?
At regex101, select JavaScript option when testing JS patterns.
Ah, I see. Thank you!
1

[A-Za-z]{4}: Alphabet character 4 times.

+: Match one or more times. [A-Za-z]{4} follows by + is a wrong pattern.

[0-9]{4}: Nummeric 4 times. It can be short hand by \d{4}.

Then, you can remove required attribute because it's combined in the pattern.

Correct regex: [a-zA-Z]{4}[0-9]{4} or [a-zA-z]{4}\d{4}

2 Comments

Then, [A-Za-z]{4} one or more times. is a wrong pattern explanation. The {4}+ was tested with PCRE option, and it was parsed as a possessive quantifier. And {4}+ = {4} in PCRE. In JS regex, quantifiying a quantifier is not allowed (except for cases like {1}? when the ? makes a lazy limiting quantifier pattern - but again, it makes sense if both bounds are specified, as in {1,4}?).
@WiktorStribiżew Thanks! I've just edited the explaining
1

Try this also,

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

You can try this pattern as well, but I think some editors not support this,

[\u\l]{4}\d{4}

[\u\l] matches uppercase and lowercase letters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.