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';

public function validatePostalCode($countryId,$postalCode){
  // how?
  if($valid) return true;
  else return false;

This should work:

public function validatePostalCode($countryId,$postalCode){
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $postCodeValidator = $objectManager->create(\Magento\Directory\Model\Country\Postcode\ValidatorInterface::class);
  return (bool) $postCodeValidator->validate($postalCode,$countryId);
  • 1
    Direct use of object manager is not recommended, kindly use constructor dependency injection instead. – Anshu Mishra Sep 13 '18 at 5:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.