pip
pip

Reputation: 41

regex works, but in html form will not allow anything

I created this bit go regex in the regexer website and it worked with the things I entered, I want to to allow upper and lowercase letters but to not allow combinations over 40 characters, this is the regex...

^[a-z]|[A-Z]{1,40}$

the line of code is...

First name:<input type="text" name="firstname" pattern= ^[a-z]|[A-Z]{1,40}$>

Upvotes: 1

Views: 46

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

Try it like this: ^[a-zA-Z]{1,40}$

For the pattern attribute you could also use [a-zA-Z]{1,40}.

<input type="text" name="firstname" pattern="[a-zA-Z]{1,40}">

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

The paroblem with ^[a-z]|[A-Z]{1,40}$ is that the pattern will get parsed as /^(?:^[a-z]|[A-Z]{1,40}$)$/ and thus will match a string that only equals a lowercase ASCII letter or 1 to 40 uppercase ASCII letters (without allowing lowercase ones).

You should fix the pattern like this:

<input type="text" name="firstname" pattern="[a-zA-Z]{1,40}">
                                             ^^^^^^^^^^^^^^

This will only let users input 1 to 40 ASCII letters.

This regex will be parsed as /^(?:[a-zA-Z]{1,40})$/ by the HTML5 engine where ^ matches the start of input and $ matches the end of input.

input:invalid {
  color: red;
}
input:valid {
  color: black;
}
<form name="form1"> 
 <input type="text" name="firstname" pattern="[a-zA-Z]{1,40}" title="Please type 1 to 40 ASCII letters only.">
  <input type="Submit"/> 
</form>

Another way to control the length with a pattern is to use required maxlength="40" and then you may use a [A-Za-z]+ pattern:

input:invalid {
  color: red;
}
input:valid {
  color: black;
}
<form name="form1"> 
 <input type="text" name="firstname" pattern="[a-zA-Z]+" required maxlength="40" title="Please type 1 to 40 ASCII letters only.">
  <input type="Submit"/> 
</form>

Upvotes: 2

Related Questions