Is there a way to make magento 2 only allow 6 digit number format as customer password?
3 Answers
You have to customize the default password validation in customer registration form.
Navigate to
app/design/frontend/vendor/theme/Magento_Customer/templates/form/register.phtml
Find this line
data-validate="{required:true, 'validate-customer-password':true}"
and replace with this
data-validate="{required:true, 'validate-mycustom-password':true}"
Now add following code at the end of the file
<script type="text/javascript">
require([
'jquery',
'jquery/ui',
'jquery/validate',
'mage/translate'
], function($){
$.validator.addMethod(
'validate-mycustom-password', function (value) {
return (value.length == 6 && /^-?\d+$/.test(value));
}, $.mage.__('Password length should be 6 and only numbers are allowed'));
});
</script>
Also, change the minimum password length from
Store > Configuration > Customers > Customer Configuration > Password Options > Minimum Password length
No of characters can be restricted in below setting
Store > Configuration > Customers > Customer Configuration > Password Options > Minimum Password length.
To use numbers only, you have to extend the file and use data-validate="{'validate-number':true}"
in the password element.
Can't we simply change this directly in the template file like changing
<input name="login[password]" type="password" autocomplete="off" class="input-text" id="pass" title="Password" data-validate="{required:true}" aria-required="true">
into
<input name="login[password]" type="password" autocomplete="off" class="input-text" id="pass" title="Password" maxlength="6" pattern="\d{6}" data-validate="{required:true}" aria-required="true">
You can notice the use of maxlength="6" pattern="\d{6}" in the input box.
pattern="\d{6} would allow digit combination of 6 digits.
You will also need to set minimum characters in Magento admin to avoid conflict.