In this post I have tried to create a simple Javascript function, which allows us to enter a proper canada postal code in textbox.
<!DOCTYPE html>
<script>
function formatCanadaPostalCode(id) {
var postalcode = document.getElementById(id).value
var postcodeLength= postalcode.length;
if(postcodeLength==1 || postcodeLength==3 || postcodeLength==5){
if(postalcode.charAt(postcodeLength–1).match(/[a-zA-Z]/i)){}else{
document.getElementById(“postalcode”).value=postalcode.slice(0, – 1);
}
}else if(postcodeLength==2 || postcodeLength==4 || postcodeLength==6){
if( postalcode.charAt(postcodeLength–1).match(/[0-9]/i)){}else{
document.getElementById(“postalcode”).value=postalcode.slice(0, – 1);
}
}
}
</script>
<body>
<input id=“postalcode” type=“text” maxlength=“6”
onkeydown=“formatCanadaPostalCode(‘postalcode’)“
onkeyup=“formatCanadaPostalCode(‘postalcode’)“>
</body>
</html>
OUTPUT : M2P6A8
Feel free to try and execute this code and comment below.