Magento 2 – How to Add Custom Validation for Password

form-validationmagento2password

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?

Best Answer

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.

Related Topic