How to validate postal code by country id?
How to validate postal code by country id?
In Magento checkout there is a postal code verification for each country, now I want to implement it in different module for different case, how to do it if I already have the country id and postal code as the parameter, for example:
$postalCode = '15433';
$countryId = 'UK';
$this->validatePostalCode($countryId,$postalCode);
public function validatePostalCode($countryId,$postalCode)
// how?
if($valid) return true;
else return false;
1 Answer
1
This should work:
public function validatePostalCode($countryId,$postalCode)
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$postCodeValidator = $objectManager->create(MagentoDirectoryModelCountryPostcodeValidatorInterface::class);
return (bool) $postCodeValidator->validate($postalCode,$countryId);
Thanks for contributing an answer to Magento Stack Exchange!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Direct use of object manager is not recommended, kindly use constructor dependency injection instead.
– Anshu Mishra
Sep 13 '18 at 5:31