Reputation: 5761
I am using the following regex in conjunction with abide Foundation for validating a password:
<form id="setPassword" action="{{ url('changePasswordWithoutToken') }}" method="POST" class="account setPassword" data-abide="ajax" novalidate="novalidate">
{{ csrfToken() }}
<input type="hidden" name="token" value="{{ data.token }}"/>
<div class="row">
<div class="large-12 columns"><p>{{ 'PLEASECHOOSEAPASSWORD'|trans }}</p></div>
<div class="large-12 columns">
<label class="password" for="setPasswordField">
<input type="password" id="setPasswordField" name="setPasswordField" pattern="passwordAdditional" required placeholder="{{ 'ACCOUNTLOGINLABELPASSWORD'|trans }}" />
<small class="error">{{ 'PASSWORDSHOULDCONTAIN'|trans }}</small>
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label class="confirmPassword" for="confirmSetPassword">
<input type="password" id="confirmSetPassword" name="confirmSetPassword" data-equalto="setPasswordField" required placeholder="{{ 'CONFIRMPASSWORD'|trans }}" />
<small class="error">{{ 'ACCOUNTREGISTRATIONERRORDIFFERENTPASSWORDS'|trans }}</small>
</label>
</div>
</div>
<div class="row">
<div class="small-12 medium-5 large-4 columns">
<button type="submit" class="button" id="setPasswordBtn">{{ 'SAVECHANGES'|trans }}</button>
</div>
</div>
JS:
patterns: { passwordAdditional: /^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[_\W\S]).{8,}/ }
It deosn't seem to pick up the symbol, when I enter a new password without a symbol the validation message disappears. It shouldn't as I haven't inserted any symbol inside the new password. Is my regex wrong?
Upvotes: 2
Views: 372
Reputation: 8413
Your regex is wrong, there are 2 mistakes you made:
(?=.[a-z])
is looking ahead for a single character followed by a lowercase letter, but your intention is to find a lowercase letter in the string, so the .
should be modified by *
(0 or more times)
(?=.[_\W\S])
is looking ahead for a single character followed by either underscore or a non-word or a non-space, which is litereally everything. This seems to be your check for a symbol, but it will always match (if there are at least 2 characters). I would use a negation to achieve this, like (?=.*[^a-zA-Z0-9\s])
This leads to the following regex
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z0-9\s]).{8,}$/
You can look at https://regex101.com/r/dG9xL8/1 for a demo.
Upvotes: 5
Reputation: 3346
Hope this helps.
/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/
It needs at least 1 upper case & lower case letter, a digit and a symbol (among #?!@$%^&*-
).
Upvotes: 1