Magento – Magento 2 : How to validate email or mobile number in a textbox validation

emailmagento2mobilevalidation

  <input type="text" class="input-email-mobile " id="customer-email-mobile">

I need to validate Mobile number or email in the above text box using magento validation.! maybe the user enter mobile number or email in the same input data-validate="{required:true,'validate-email':true,'validate-number':true}this code only validate email. how can i achieve both in a text box using magento validation In Checkout Shipping Address page ??

Best Answer

Magento 2 uses validation.js file for apply validations which is located at lib/web/mage directory of Magento 2.

In Magento 2, it's not by default provide rule which validate mobile number and email ID validate in textbox.

So, Need to create new rule to extend validation.js using mixin.

1) create requirejs-config.js at app/code/RH/CustomValidation/view/frontend/

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'RH_CustomValidation/js/validation-mixin': true
            }
        }
    }
}

2) Now, Add the JS validation class using the mixin at app/code/RH/CustomValidation/view/frontend/web/js/validation-mixin.js

define([
    'jquery'
], function ($) {
    "use strict";

    return function () {
        var custom_text;
        $.validator.addMethod(
            'validate-custom-mob-email-rule',
            function (value) {
                var mob_regex = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[789]\d{9}$/;
                var email_regex = /^([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9,!\#\$%&'\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*@([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*\.(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){2,})$/;
                if (!$.mage.isEmptyNoTrim(value))
                {
                    if(email_regex.test(value) && !mob_regex.test(value)){
                        return true;
                    } else if(mob_regex.test(value) && !email_regex.test(value)){
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            },
            $.mage.__('Your validation error message')
        );
    }
});

3) Now, change class name in login.phtml file. Find "Email" Text field. Then, change field type email to text and replace validate-email validation with validate-custom-mob-email-rule new validation.

Now, upgrade, deploy and clean cache.

Cheers :)

Related Topic