2010-03-07 167 views
0

好的,我有一個驗證腳本,用於檢查表單上的所有內容 - 但它會將電話號碼字段標記爲錯誤,而不管內容是什麼。我嘗試了幾種不同的方法,我無法弄清楚我做錯了什麼。表單驗證問題(電話號碼)

,用於驗證是腳本的一部分...

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) 

加入:

另外,請記住,在布爾上下文中評估時,您不必與真或假進行比較。 (使用值本身或否定)。而正是他們的意思後更好地名稱的變量,而不是「trueorfalse」這是我重新寫:

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 2010-03-07 02:11:46

0

不是一個實際的回答你的問題,因爲沒有什麼內在的錯誤您發佈的片段,但是這是對於評論太大。

你的代碼真的是多餘的!

您可以表達整個第一部分爲:

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; 
} 

不算多更容易閱讀?