2010-03-07 6 views
0

좋아요, 양식의 모든 것을 확인하는 유효성 검사 스크립트가 있습니다.하지만 전화 번호 필드에는 whats와 상관없이 잘못된 것으로 플래그가 지정됩니다. 나는 그것을 여러 가지 방법으로 시도해 왔으며 내가 잘못하고있는 것을 파악할 수 없다.폼 유효성 검사 문제 (전화 번호)

입니다 유효성을 검사하는 스크립트의 일부 ...

if (testPattern(phone1, /^\d{3}$/)== false) { // checking phone length 
     valid = false; 
    } 
    if (testPattern(phone2, /^\d{3}$/)== false) { 
     valid = false; 
    } 
    if (testPattern(phone3, /^\d{4}$/)== false) { 
     valid = false; 
    } 

함수 코드는 ...

function testPattern(field, reg2) { 
    var trueOrfalse = reg2.test(field) 
    if (trueOrfalse == false) { 
     field.style.backgroundColor="yellow"; // if false, change colors and return false 
     field.style.color="red"; 
     return false; 
    } 
    else { 
     field.style.backgroundColor="white"; // if true, change colors and return true 
     field.style.color="black"; 
     return true; 
    } 
} 

답변

3

어쩌면

var trueOrfalse = reg2.test(field) 

는해야

var trueOrfalse = reg2.test(field.value) 

올린 날짜 :

또한 부울 컨텍스트에서 평가할 때 true 또는 false와 비교할 필요가 없습니다. 값 자체 또는 부정을 사용하십시오. 당신이 게시 된 조각 본질적으로 아무 문제가 없기 때문에,

if (!testPattern(phone1, /^\d{3}$/)) { // checking phone length 
    valid = false; 
} 
if (!testPattern(phone2, /^\d{3}$/)) { 
    valid = false; 
} 
if (!testPattern(phone3, /^\d{4}$/)) { 
    valid = false; 
} 



function testPattern(field, reg2) { 
    var good = reg2.test(field.value); 
    if (good) { 
     field.style.backgroundColor="white"; // if good, change colors 
     field.style.color="black"; 
    } 
    else { 
     field.style.backgroundColor="yellow"; // if bad, change colors 
     field.style.color="red"; 
    } 
    return(good); 
} 
+0

+1은 변수의 의미대로 변수의 이름을 지정하도록 지정합니다. – Cam

0

하지 질문에 대한 실제 대답,하지만이 있었다 : 그리고 그 의미 후 이름 변수에 더하지 "trueorfalse은"여기 내 다시 쓰기입니다 댓글에 너무 큽니다.

코드가 실제로 중복됩니다!

valid = testPattern(phone1, /^\d{3}$/) && 
     testPattern(phone2, /^\d{3}$/) && 
     testPattern(phone3, /^\d{4}$/) 

그리고 기능 코드로 :

function testPattern(field, reg2) { 
    var test_result = reg2.test(field) 

    if (test_result) { 
     field.style.backgroundColor = "white"; 
     field.style.color = "black"; 
    } else { 
     field.style.backgroundColor = "yellow"; 
     field.style.color = "red"; 
    } 

    return test_result; 
} 

또는 더 간결 :

function testPattern(field, reg2) { 
    var test_result = reg2.test(field) 

    field.style.backgroundColor = test_result ? "white" : "yellow"; 
    field.style.color = test_result ? "black" : "red"; 

    return test_result; 
} 

그 정도되지 않습니다 당신은 등 전체 첫 번째 부분을 표현할 수

읽기 쉽니?