Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML pattern validation always false

I'm trying to perform a client-side check for a password insertion form in HTML, I need the password to contain at least an alphabetic character and a number. I tried with the following:

<input type="password" name="reg-password" pattern="(?=.*\d)(?=.*[a-zA-Z])" title="The password must contain at least a number and an alphabetic character" required>

but for some reason which I'm not understanding the validation always fails and I cannot submit the form. Could you please explain me where my code is wrong? I also tested the regex with some online regex debuggers and it should be ok. Thanks in advance.

Also, is there any particular reason for which I should avoid this methods of client-side validation and use Javascript code instead? I find this way much faster (if it only worked)

like image 850
RVKS Avatar asked Apr 15 '26 23:04

RVKS


1 Answers

Since HTML5 input pattern requires a full string match, use the following:

pattern="(?=.*\d)(?=.*[a-zA-Z]).+"

It will get translated to /^(?:(?=.*\d)(?=.*[a-zA-Z]).+)$/ regex and will correctly handle the input.

In case you are using some additional frameworks that override HTML5 pattern attribute handling, add the anchors explicitly:

pattern="^(?=.*\d)(?=.*[a-zA-Z]).+$"

and it will work in all contexts.

JS demo:

<form>
<input type="password" name="reg-password" pattern="^(?=.*\d)(?=.*[a-zA-Z]).+" title="The password must contain at least a number and an alphabetic character" required>
<input type="submit">
</form>
like image 89
Wiktor Stribiżew Avatar answered Apr 18 '26 13:04

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!