Adding UK postcode form validation to Magento
Out of the box Magento doesn't have the ability to, on the client side (using JS), validate UK postcodes (for example in the Checkout process). Therefore this article aims to show a workaround to achieve this.
Rather than some solutions, this doesn't require you to edit each template file you have a postcode field in! All you need to do once the process below has been implemented, is add a specific CSS class to the input field... simples!
There is one caveat, it does modify a core Magento file! Perhaps make a back-up of this file for now, or if you're using version control - no worries. The file being modified file is: /js/prototype/validation.js (which uses the Really Easy Field Validation library for those interested).
Open /js/prototype/validation.js and add the following lines:
Go to line 414 and youāll notice the function āValidation.addAllTheseā, just paste in the same way you see the others are formatted.Ā
['validate-postcode', 'Please enter a valid postcode', function(v) { return Validation.get('IsEmpty').test(v) || /(^[A-Z]{1,2}[0-9R][0-9A-Z]?[\s]?[0-9][ABD-HJLNP-UW-Z]{2}$)/i.test(v); }],
Then whenever you wish to use the validation, add a class of āvalidate-postcodeā to your form text field. E.g:
<input type="text" name="postcode" value="" title="<?php echo $this->__('Postcode') ?>" class="input-text validate-postcode required-entry" id="postcode" />