Created
May 14, 2013 20:41
-
-
Save djanix/5579359 to your computer and use it in GitHub Desktop.
Canada postal code validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(function ($) { | |
var normalizePostalCode = function (postalCode) { | |
return postalCode.replace(/[^a-z0-9]/gi, '').toUpperCase(); | |
}; | |
var formatPostalCode = function (postalCode) { | |
var regex = /^([abceghjklmnprstvwxyz][0-9][abceghjklmnprstvwxyz])([0-9][abceghjklmnprstvwxyz][0-9])$/i; | |
var normalized = normalizePostalCode(postalCode); | |
var matches = normalized.match(regex); | |
if (matches) { | |
return matches[1] + ' ' + matches[2]; | |
} | |
return false; | |
}; | |
$('#test').submit(function (event) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
var input = $('#postalCode'); | |
var formattedPostalCode = formatPostalCode(input.val()); | |
if (formattedPostalCode) { | |
input.val(formattedPostalCode); | |
} else { | |
alert('invalid postal code'); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment