|
| 1 | +/** |
| 2 | + * Copyright © Magento, Inc. All rights reserved. |
| 3 | + * See COPYING.txt for license details. |
| 4 | + */ |
| 5 | + |
| 6 | +define([ |
| 7 | + 'jquery', |
| 8 | + 'Magento_Checkout/js/model/postcode-validator', |
| 9 | + 'mage/translate', |
| 10 | + 'uiRegistry' |
| 11 | + ], function ( |
| 12 | + $, |
| 13 | + postcodeValidator, |
| 14 | + $t, |
| 15 | + uiRegistry |
| 16 | +) { |
| 17 | + 'use strict'; |
| 18 | + |
| 19 | + var postcodeElementName = 'postcode'; |
| 20 | + |
| 21 | + return { |
| 22 | + validateZipCodeTimeout: 0, |
| 23 | + validateDelay: 2000, |
| 24 | + |
| 25 | + /** |
| 26 | + * Perform postponed binding for fieldset elements |
| 27 | + * |
| 28 | + * @param {String} formPath |
| 29 | + */ |
| 30 | + initFields: function (formPath) { |
| 31 | + var self = this; |
| 32 | + |
| 33 | + uiRegistry.async(formPath + '.' + postcodeElementName)(self.bindHandler.bind(self)); |
| 34 | + }, |
| 35 | + |
| 36 | + /** |
| 37 | + * @param {Object} element |
| 38 | + * @param {Number} delay |
| 39 | + */ |
| 40 | + bindHandler: function (element, delay) { |
| 41 | + var self = this; |
| 42 | + |
| 43 | + delay = typeof delay === 'undefined' ? self.validateDelay : delay; |
| 44 | + |
| 45 | + element.on('value', function () { |
| 46 | + clearTimeout(self.validateZipCodeTimeout); |
| 47 | + self.validateZipCodeTimeout = setTimeout(function () { |
| 48 | + self.postcodeValidation(element); |
| 49 | + }, delay); |
| 50 | + }); |
| 51 | + }, |
| 52 | + |
| 53 | + /** |
| 54 | + * @param {Object} postcodeElement |
| 55 | + * @return {*} |
| 56 | + */ |
| 57 | + postcodeValidation: function (postcodeElement) { |
| 58 | + var countryId = $('select[name="country_id"]:visible').val(), |
| 59 | + validationResult, |
| 60 | + warnMessage; |
| 61 | + |
| 62 | + if (postcodeElement == null || postcodeElement.value() == null) { |
| 63 | + return true; |
| 64 | + } |
| 65 | + |
| 66 | + postcodeElement.warn(null); |
| 67 | + validationResult = postcodeValidator.validate(postcodeElement.value(), countryId); |
| 68 | + |
| 69 | + if (!validationResult) { |
| 70 | + warnMessage = $t('Provided Zip/Postal Code seems to be invalid.'); |
| 71 | + |
| 72 | + if (postcodeValidator.validatedPostCodeExample.length) { |
| 73 | + warnMessage += $t(' Example: ') + postcodeValidator.validatedPostCodeExample.join('; ') + '. '; |
| 74 | + } |
| 75 | + warnMessage += $t('If you believe it is the right one you can ignore this notice.'); |
| 76 | + postcodeElement.warn(warnMessage); |
| 77 | + } |
| 78 | + |
| 79 | + return validationResult; |
| 80 | + } |
| 81 | + }; |
| 82 | +}); |
0 commit comments