MaxMage / international-telephone-input

Integration to Magento 2 a jQuery plugin for entering and validating international telephone numbers.
Open Software License 3.0
27 stars 44 forks source link

Add frontend validation and set preferredCountry from admin #15

Closed VincentBean closed 2 years ago

VincentBean commented 4 years ago

This PR adds front end validation and the ability to set the preferredCountry from the Magento 2 backend as not all stores have the _general/store_information/countryid config value set

Axel29 commented 3 years ago

Hi,

First of all thank you, I was looking for this and this PR helped a lot.

There are a few errors in your JS file, you used the variable validatorObj instead of validator and your error message condition is reversed (if (isValid) instead of if (!isValid)).
In a nutshell, it should look like this:

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

    return function (validator) {

        const errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];

        let validatorObj = {
            message: '',
            validate: function (value) {
                var countryCode = $(".selected-flag .iti-flag").attr('class');

                if (countryCode === undefined) {
                    this.message = errorMap[1];
                    return false;
                }

                countryCode = countryCode.split(' ')[1];

                var isValid = intlTelInputUtils.isValidNumber(value, countryCode);
                var errorCode = intlTelInputUtils.getValidationError(value, countryCode);

                if (!isValid) {
                    this.message = errorMap[errorCode];
                }

                return isValid;
            },
        }

        validator.addRule(
            'validate-phone-number',
            validatorObj.validate,
            $.mage.__(validatorObj.message)
        );

        return validator;
    };
});