Magento2 How to add custom validation for password?
-
07-02-2021 - |
문제
I want to change default validation for all password field.
I want to change for all password field and validation is minimum 8 characters and at least one number include.
Can anyone help me with this?
해결책 2
@chirag, Thanks for your suggestion and from your suggestion i have made changes in register.phtml file and now my requirement is working. Please check below my code.
app/design/frontend/Custom/theme/Magento_Customer/templates/form/register.phtml
I have added below script.
<script type="text/javascript">
require([
'jquery',
'jquery/ui',
'jquery/validate',
'mage/translate'
], function($){
$.validator.addMethod(
'validate-mycustom-password', function (value) {
return (value.length >= 8 && /^(?=.*?[0-9]).{8,}$/.test(value));
}, $.mage.__('Minimum 8 characters with at least one number'));
});
</script>
다른 팁
If you want to validate customer login password then override phtml file in to your design folder like below.
app/design/frontend/vendor/theme/Magento_Customer/templates/form/login.phtml
Find the line data-validate="{required:true, 'validate-password':true}"
And replace with data-validate="{required:true, 'validate-mycustom-password':true}"
Add the 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>
Don't forgot to run necessary command like static:content:deploy
& cache:flush
Note: I give a validation for Max limit & allow only number. you have to customize script as per your requirement.
This is available in configuration item in the Admin Panel
In Stores > Configuration > Customers > Customer Configuration > Password Options there are options like Minimum Password Length and Number of Required Character Classes