The following code is used for formatting the phone number in javascript. Eg: 1. Input: 1234567890 Output: 123-456-7890 2. Input: 0444322567 Output: 044-432-2567
It also validated, whether if the given input is valid number.
function formatPh(ph, type) { var phObj = document.getElementById(ph); type = phObj.value; var phNum = phObj.value; var isHypen = /\-/g; var phDigit = /^\d{10}$/; var phNos = "1234567890-"; var validFormat = /^\d{3}\-\d{3}\-\d{4}$/ var notZeroHypen =
/^([0-9][0-9][1-9]|[0-9][1-9][0-9]|[1-9][0-9][0-9])\-([0-9][0-9][1-9]|[0-9][1-9][0-9]|[1-9][0-9][0-9])\-([0-9][0-9][0-9][1-9]|[0-9][1-9][0-9][0-9]|[0-9][0-9][1-9][0-9]|[1-9][0-9][0-9][0-9])$/; var notZero =
/^([0-9][0-9][1-9]|[0-9][1-9][0-9]|[1-9][0-9][0-9])([0-9][0-9][1-9]|[0-9][1-9][0-9]|[1-9][0-9][0-9])([0-9][0-9][0-9][1-9]|[0-9][1-9][0-9][0-9]|[0-9][0-9][1-9][0-9]|[1-9][0-9][0-9][0-9])$/; for(var i = 0; i <= phNum.length-1; i++) { if(phNos.indexOf(phNum.substring(i, i+1)) == -1) { alert("Not a valid "+ type +" Number \n"+ type +" Number format should be like this 123-456-7890"); return; } } if(isHypen.test(phNum)) { if(validFormat.test(phNum) && notZeroHypen.test(phNum)) { phObj.value = phNum; } else { alert("Not a valid "+ type +" Number \n"+ type +" Number format should be like this 123-456-7890"); return; } } else { if(phDigit.test(phNum) && notZero.test(phNum)) { phObj.value = phNum.substring(0, 3) + "-" + phNum.substring(3, 6) + "-" + phNum.substring(6, 10); } else { alert("Not a valid "+ type +" Number \n"+ type +" Number format should be like this 123-456-7890"); return; } } }
The formatPh(ph, type) method is getting the two parameters. ph -> the input control id type -> type of the input. it specifies whether the number is phone, mobile, etc.
|
No responses found. Be the first to respond and make money from revenue sharing program.
|