Link to home
Start Free TrialLog in
Avatar of Rajesh_mj
Rajesh_mjFlag for Afghanistan

asked on

How to format zip code using javascript

Hi Experts,

How to format zip code .The situation is if we enter a 9 digit code then it will be formatted to
***** - ****(5digits-4digits).also another condition is if we enter 7 digit code then it is formatted to
**** - ***(4digits - 3 digits). while leaving

Thanks in Advance
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Like this:

<script>
function setZip(theField){
  var num = theField.value.replace(/\D/g,"");
  if(num.length==7){
    theField.value = num.substr(0,4)+"-"+num.substr(4);
  }
  if(num.length==9){
    theField.value = num.substr(0,5)+"-"+num.substr(5);
  }

}
</script>
<body>
<form>
<input type="text" name="zip" onBlur="setZip(this)">
</form>
</body>

Avatar of Rajesh_mj

ASKER

Hi,
     Thanks for the reply first............

The above is ok but there is one problem exist because we restrict the MaxLength of the Text box by "10".So the user can enter total 10 characters

For eg: The user can able to enter like this 55555-5555    Total length =10
In this case no need for formatting.The other case is
2)There is other possibility is to enter 5555555555  Total length = 10, in this case how we format this one.This is th eproblem mainly i face..

Thanks
For that you need the built in method doWhatImean(;-)
Take spacial care for the passed parameters ;-)

ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial