1

I'm trying to create pattern for few different input fields. First two fields are first and last name. Then I have gender and grade. Here is what I have created:

<input type="text" name="lname" id="lname" value="" size="20" maxlength="30" title="Maximum length 30 characters." pattern="/^ *[a-z][a-z' .,-]{0,29} *$/i" required />
<input type="text" name="fname" id="fname" value="" size="20" maxlength="30" title="Maximum length 30 characters." pattern="/^ *[a-z][a-z' .,-]{0,29} *$/i" required />
<input type="text" name="gender" id="gender" value="" size="1" maxlength="1" title="Maximum length 1 character." pattern="/^ *([M|F])? *$/i" required />
<input type="text" name="garde" id="grade" value="" size="2" maxlength="2" title="Maximum length 2 characters." pattern="/^ *(0?[0-9]|1[0-2]|[A-Z]{1,2})? *$/i" required />

None of the regular expressions works. I'm not sure if I'm using correct syntax's or something else is problem in my code. For first and last name field should allow 30 charters max, alphabetic charters including ' .,-. Gender should allow m or f or M or F. Grade field should allow upper/lower case letters or numeric, no longer than 1 character. If anyone can help please let me know. Thank you.

5
  • 1
    You cannot use regex literals in HTML5 pattern attributes. Commented Jul 31, 2017 at 14:34
  • @WiktorStribiżew What I can use? Can you provide an example please? Commented Jul 31, 2017 at 14:35
  • E.g. pattern=" *[a-zA-Z][A-Za-z' .,-]{0,29} *" for the first one. Commented Jul 31, 2017 at 14:36
  • The third one: pattern=" *[MmFf]? *" Commented Jul 31, 2017 at 14:38
  • @WiktorStribiżew That works! Thanks a lot. If you want to write the answer I will mark as correct answer. Commented Jul 31, 2017 at 14:46

1 Answer 1

1

You cannot use regex literals in HTML5 pattern attributes. You need to literally add A-Za-z to the character classes. Also note that ^ and $ anchors are implied, i.e. the patterns are enclosed with ^(?: and )$ automatically by HTML5 engine.

Thus, you patterns will look like

pattern=" *[a-zA-Z][A-Za-z' .,-]{0,29} *"
pattern=" *[MmFf]? *"

and so on.

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

Comments

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.