1

I'm dabbling with Form Validation using HTML5 patterns. I would like for my input field to allow any combination of only the following characters.

, @ – - . ; / ' : ( ) # a-z A-Z 0-9 space

I've been trying to create the pattern to accomplish this. I thought I came up with a solution using regexr.com. On that site my pattern works great, but when implemented in my form everything shows up as an invalid entry. For example 'Test' is invalid 'Test D'luxe' is invalid, 'Company Test #1' is invalid, etc.

My Results on RegExr

Here is the pattern I've come up with:

pattern="[a-zA-Z[\d\[\-\.\_,\(\)\#\:\;\'\/]"

I've looked at a few other stack overflow posts such as

but I've been unable to piece together what I'm doing incorrectly. I would appreciate any help. I'm very new to this so I'm open to any and all feedback.

Community
  • 1
  • 1
Matt G.
  • 105
  • 2
  • 12

1 Answers1

2

You should allow 0+ characters by adding a * quantifier at the end, replace ' with \x27 and get rid of the redundant escaping:

pattern="[-,@–.;/\x27:()#a-zA-Z0-9 ]*"

input:valid {
  color: green;
}
input:invalid {
  color: red;
}
<form name="form1"> 
 <input value="-,@–.;/':()#azAZ09 " pattern="[-,@–.;/\x27:()#a-zA-Z0-9 ]*" title="Please enter allowed characters only."/>
 <input type="Submit"/> 
</form>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563