Ivan Lendl
Ivan Lendl

Reputation: 87

HTML5 Regex Pattern for textbox validation: allow alphabet, spaces, and hyphens only

I am creating a form in html and for my first and last name text inputs, I want to have a regex validation on them that only allows the user to input: letters of the alphabet, spaces, and hyphens.

I have tried this pattern but to no avail:

[A-Za-z -]

My HTML code:

<input type="text" id="first_name" name="first_name" maxlength="25" required="required" pattern="[A-Za-z -]"/>

I know how to get only alphabet characters, but allowing spaces and hyphens only is something I'm unable to manage.

Upvotes: 2

Views: 25827

Answers (1)

Toto
Toto

Reputation: 91385

Add anchors and a quantifier:

^[A-Za-z -]+$

Upvotes: 8

Related Questions