Phone number format using Java Script
-
Hi, I have a requirement where i need to format the phone number in 111-111-1111 format after it loses focus. Can any one help me how to do this? Santhapur
I was curious, so whipped up a test page: function formatValue() { var v = document.getElementById('val').value; var fv = document.getElementById('fval'); var re = /^(\d{3})[-]?(\d{3})[-]?(\d{4})$/ if(re.test(v) == true) { fv.innerHTML = RegExp.$1 + "-" + RegExp.$2 + "-" + RegExp.$3; } else { fv.innerHTML = "Bad!"; } }
The magic is in the regex. You can tweak it to accept other delimiters other than "-". - S 50 cups of coffee and you know it's on! A post a day, keeps the white coats away!
-
I was curious, so whipped up a test page: function formatValue() { var v = document.getElementById('val').value; var fv = document.getElementById('fval'); var re = /^(\d{3})[-]?(\d{3})[-]?(\d{4})$/ if(re.test(v) == true) { fv.innerHTML = RegExp.$1 + "-" + RegExp.$2 + "-" + RegExp.$3; } else { fv.innerHTML = "Bad!"; } }
The magic is in the regex. You can tweak it to accept other delimiters other than "-". - S 50 cups of coffee and you know it's on! A post a day, keeps the white coats away!
-
Hey Thanks Its working but.. But i need to display the formatted output again in the textbox itself. How can we do it ? Please help me i am a begineer in the javascript programming. Or else give me a small clue i can try it out.. Santhapur
In my sample, replace: fval.innerHTML = RegExp.$1 + "-" + RegExp.$2 + "-" + RegExp.$3; with: document.getElementById('val').value = RegExp.$1 + "-" + RegExp.$2 + "-" + RegExp.$3; You can work out the best way of handling bad input however you want, maybe an alert or an error message.
- S 50 cups of coffee and you know it's on! A post a day, keeps the white coats away!
-
In my sample, replace: fval.innerHTML = RegExp.$1 + "-" + RegExp.$2 + "-" + RegExp.$3; with: document.getElementById('val').value = RegExp.$1 + "-" + RegExp.$2 + "-" + RegExp.$3; You can work out the best way of handling bad input however you want, maybe an alert or an error message.
- S 50 cups of coffee and you know it's on! A post a day, keeps the white coats away!
-
Glad to help, and I learned something new today. :)
- S 50 cups of coffee and you know it's on! A post a day, keeps the white coats away!
-
There are several good articles on this site in regards to regular expressions and the Expresso tool for building regular expressions. I suggest you check them out during your free time :)
"The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon "Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham