1

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.

1
  • It should work. What error do you get? Commented Dec 29, 2018 at 15:21

2 Answers 2

3

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>

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

Comments

0

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-]

Demo

2 Comments

I tried your syntax with the following string '2WestStreetL341LQ' and I get 'Invalid format.' returned by Firefox
Strange, it works on your regex checker but not in Firefox Quantum 64.0 (64-bit)

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.