Techoceanhub logo

Canada postal code Javascript formatter/validator function

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 postcodeLengthpostalcode.length;      
            if(postcodeLength==1 || postcodeLength==3 || postcodeLength==5){
                if(postalcode.charAt(postcodeLength1).match(/[a-zA-Z]/i)){}else{
                    document.getElementById(“postalcode”).value=postalcode.slice(0, – 1);
                }
            }else if(postcodeLength==2 || postcodeLength==4 || postcodeLength==6){
                ifpostalcode.charAt(postcodeLength1).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.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .