Monday, May 14, 2012

Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.



Here's the phone number with dashes form that is working:



//Validates phone number with dashes. 
function isTwelveAndDashes(phone) {

if (phone.length != 12) return false;

var pass = true;

for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);

if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}

return pass;
}?


and this is the one I can't manage to work out.



function isTwelveAndPara(phone) {
if (phone.length != 12) return false;

var pass = true;

for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);

if (i == 0) {
if (c != '(') {
pass = false;
}
}

if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}

return pass;
}?




No comments:

Post a Comment