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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With