Magento2 How to add custom validation for password?

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.


@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>