pr0cz
pr0cz

Reputation: 507

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.

Upvotes: 1

Views: 96

Answers (3)

Kushan
Kushan

Reputation: 10695

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.

Upvotes: 1

Sebastian Brosch
Sebastian Brosch

Reputation: 43564

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

Upvotes: 3

T&#226;n
T&#226;n

Reputation: 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}

Upvotes: 1

Related Questions