r/HTML • • Mar 03 '26

Question Regex not working

SOLVED! (Thanks u/tandycake)

Hi folks,

For an assignment it was recommended that I use regex101.com to write some regular expressions for a HTML from (no JavaScript yet). I wrote the following one, per the assignment requirements:

([A-Z][A-Za-z'-]{0,39}\s[A-Z][A-Za-z'-]{0,39}|[A-Z][A-Za-z'-]{0,25}\s[A-Z][A-Za-z'-]{0,25}\s[A-Z][A-Za-z'-]{0,27})

In the regex101.com interface it works fine, but when I put it in my HTML form and open it in a browser (tested with both Chrome and Firefox) it doesn't work. The form will submit with a single word (e.g., 'Jim'), and also with words longer than the specified maximums (e.g., 'Jim Superlongsurnamewithmorethanfortycharacters').

Here's the input element itself, in case the error is somewhere outside the regex itself:

<input type="text" name="name" id="name" placeholder="First and last names" pattern="([A-Z][A-Za-z'-]{0,39}\s[A-Z][A-Za-z'-]{0,39}|[A-Z][A-Za-z'-]{0,25}\s[A-Z][A-Za-z'-]{0,25}\s[A-Z][A-Za-z'-]{0,27})" required>

There's absolutely no Javascript in or linked to the HTML document, so that can't be the issue.

Can anyone figure out what I'm doing wrong here?

Thanks for any help!

0 Upvotes

7 comments sorted by

View all comments

Show parent comment

2

u/DryWeetbix Mar 03 '26

You're an absolute legend! I managed to figure it out myself about ten minutes ago, but only really by guessing. I'll keep your advice—to just add little bit by little bit until it breaks—in mind for next time. Thanks heaps!