Reputation: 2722
I am creating a form in html and for a text input, I want to have a regex validation on it that only allows the user to input: letters of the alphabet, numbers and certain characters;
/ - forward slash
- - hyphen
. - period (full stop)
& - ampersand
- spaces
I have tried this pattern but to no avail:
[a-zA-Z0-9\/\-\.\&\ ]
My HTML code:
<input type="text" id="payment_reference" name="payment_reference" maxlength="18" value="' . $payment_reference_default . '" pattern="[a-zA-Z0-9\/\-\.\&\ ]" required>
I know how to get only alphabet characters and numbers, but allowing the other characters as well is something I'm unable to manage.
Upvotes: 1
Views: 3605
Reputation: 626845
2023 Update
Now, you need to always escape the literal hyphen inside character classes at the end of the character class, so use
pattern="[a-zA-Z0-9/.& \-]+"
Originial answer
You need to remove escaping from every non-special char because in FF (and Chrome) the HTML5 regex is compiled with u
modifier, and it lays bigger restriction on the pattern. To enable matching 1 or more allowed chars, add +
after the character class:
pattern="[a-zA-Z0-9/.& -]+"
Note that all special chars in your pattern except -
are not special inside a character class. Hence, only -
can be escaped, but it is common to put it at the start/end of the character class to avoid overescaping.
input:valid {
color: black;
}
input:invalid {
color: red;
}
<form name="form1">
<input pattern="[a-zA-Z0-9/.& -]+" title="Please enter the data in correct format." />
<input type="Submit"/>
</form>
Upvotes: 3
Reputation: 37755
You need to escape character properly.
-
i am not escaping it here because when you use it as first or last character in character class you don't need to escape
[a-zA-Z0-9\/.&\s-]
Upvotes: 0