2013-05-29 82 views
1

我試圖驗證使用javascript的窗體。在返回true之前檢查輸入值是否與數組中的任何值匹配。在返回true之前檢查輸入值是否與數組中的任何值匹配

這是我迄今爲止寫的一個例子。但這似乎不起作用。

<script type='text/javascript'> 

function checkForm() 
{ 

var agent = document.getElementById('agent').value; 

var myArray = new Array() 
    myArray[0] = 'First Agent'; 
    myArray[1] = 'Second Agent'; 
    myArray[2] = 'Third Agent'; 

if (agent != myArray) 
{ 
    alert("Invalid Agent"); 
    return false; 
} 

else 
{ 
    return true; 
} 
} 

<form> 
<fieldset> 
Agents Name* 
<input type="text" size="20" name="agent" id="agent"> 
</fieldset> 
</form> 
+0

我建議使用jQuery驗證https://www.google.com/url?sa=t&rct= J&q =&ESRC = S&源=幅和CD = 1&CAD = RJA&VED = 0CDEQFjAA&URL = HTTP%3A%2F%2Fjqueryvalidation.org%2Fvalidate%2F&EI = lU2mUfD-JpK88wSjjoGQCw&USG = AFQjCNE43XLONaPQUHt0-BNtFoJG-FSa3Q&SIG2 = RTM-Oa3AUbwRYDiWfwtyWA&BVM = bv.47008514,d.eWU插件。我有一個巨大的表單,我需要驗證,這個插件使得管理變得非常簡單。 – ckpepper02

回答

0
function checkForm() { 
    var agent = document.getElementById('agent').value; 
    var myArray = ['First Agent', 'Second Agent', 'Third Agent']; 
    if(myArray.indexOf(agent) == -1) //returns the index of the selected element 
    { 
     alert("Invalid Agent"); 
     return false; // if you return false then you don't have to write the else statement 
    } 
    return true; 
} 
+0

謝謝你的幫助 – user2433761

3

你需要做的結構來傳遞你的整個數組,當值匹配你返回true,否則返回false。類似這樣的:

for (var i = 0; i < myArray.length; i++) { 
    if (agent == myArray[i]) 
     return true; 
} 
return false; 
-1

以下劃線/ lodash你可以這樣做:

if (_.indexOf(myArray,agent) == -1) 
{ 
    //alert invalid agent  
    ... 
} 
相關問題