Sanitize and validate ZIP codes in Magento using Prototype's Validation
/**
* A simple ZIP code validator and sanitizer
*
* @author Hervé Guétin <@herveguetin> <herve.guetin@agence-soon.fr>
*/
var zipSanitizer = {
// All sanitizers available
sanitizers: {},
// Add a sanitizer
add: function(o) {
this.sanitizers[o.countryCode] = function() {
// Add Prototype validation
if(typeof o.validationRegex !== 'undefined') {
Validation.add('sanitize-zip-' + o.countryCode, 'Please enter a valid zip code.', function(v) {
return Validation.get('IsEmpty').test(v) || o.validationRegex.test(v);
});
}
// Append sanitizing function
if(typeof o.sanitize !== 'undefined') {
$$('.sanitize-zip-' + o.countryCode).each(function(el) {
o.sanitize(el);
el.observe('keyup', function() {
o.sanitize(el);
})
});
}
};
},
// Sanitize a ZIP code input based on selected country
sanitize: function(countryCode, zipInput) {
// Remove any existing sanitizer on ZIP input element
var currentClassNames = zipInput.classNames().toArray();
currentClassNames.each(function(className) {
if(className.indexOf('sanitize-zip-') > -1) {
zipInput.removeClassName(className);
zipInput.stopObserving('keyup');
}
});
// Configure and sanitize ZIP input element
zipInput.addClassName('sanitize-zip-' + countryCode);
if(typeof this.sanitizers[countryCode] !== 'undefined') {
this.sanitizers[countryCode]();
}
}
};
/**
* Create a sanitizer for France
*/
zipSanitizer.add({
countryCode: 'FR', // Country as in country_id element select options
validationRegex: /^\d{5}$/, // Validation regex for Prototype Validation
sanitize: function(el) { // What to do to make sure ZIP input is correct?
var value = el.getValue();
value = value.replace(/\D/g, '');
value = value.substr(0, 5);
el.setValue(value);
}
});
/**
* Once DOM is loaded...
*/
;document.observe("dom:loaded", function() {
// Gather all country_id select of page
var countryInputs = $$('[name="country_id"]');
// For each country_id inputs...
countryInputs.each(function(el) {
// ... find its related ZIP input element
var zipInput = el.up('div.fieldset').down('[name="postcode"]');
// If there is country that is selected by default, sanitize it staight away!
if(el.getValue() !== undefined && el.getValue() !== '') {
zipSanitizer.sanitize(el.getValue(), zipInput);
}
// And make sure this ZIP input is sanitized on each country change
el.observe('change', function() {
zipSanitizer.sanitize(el.getValue(), zipInput);
});
});
});