2014-02-20 33 views
0

我想驗證使用JavaScript的輸入,我想要的是如果用戶輸入一些未包括在我的數組中的提示警報。JS檢查輸入是否在數組範圍內

這裏是我迄今爲止

var validAr = ["1","2","3","4","5","6","7","8","9","10","m","M"]; 
//dont mind the i it's been previously declared 
val =+ document.getElementById('arrow_' + i + '_1').value 

alert(val); 
alert(validAr.indexOf(val)); 

例如,如果在用戶上面進入「5」,我會提醒「5」的val然後將值-1,這意味着它不屬於數組。我該如何解決這個問題?

+0

我想你最好使用正則表達式進行這種驗證。這裏是一個有用的參考http://tech.pro/tutorial/1214/javascript-regular-expression-enlightenment – Strikers

回答

3

你的數組包含字符串,但你的價值轉化爲數字:

val = +document.getElementById('arrow_'+i+'_1').value 
// ^Remove this to keep the value as a string 

由於Array.prototype.indexOf執行它未能找到數組中的值全等比較。

可以更換您的陣列實際數字的值,但由於"m""M"不會轉換爲數字就不是這樣的(當您試圖強迫他們你會NaN結束) 。

+0

是的,現在我明白了,即時將其轉換爲數字,因爲我以後需要它。轉換爲字符串只用於驗證,並正常工作。 – LefterisL

1

只是轉換你的價值在字符串

alert(validAr.indexOf(val.toString())); 

,也從+的document.getElementById刪除+( '箭頭_' + I + '_ 1')。值

所以你的代碼會

var validAr = ["1","2","3","4","5","6","7","8","9","10","m","M"]; 
//dont mind the i it's from a for above 
val = document.getElementById('arrow_'+i+'_1').value; 

alert(val); 
alert(validAr.indexOf(val.toString())); 
+0

是的,我以後使用+因爲我需要它的數量。這解決了它。謝謝 – LefterisL

0

嘗試

$(document).ready(function() { 
     var validAr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "m", "M"]; 

     $("#text").change(function() { 
      if (jQuery.inArray($(this).val(), validAr) == -1) { 
       alert("exception"); 
      } 
     }); 
    }); 

<input type="text" id="text" /> 
+0

爲什麼不只是跟着<0? – LefterisL

+0

@jogesh_pi我已經檢查過它。它的工作正常 –

0

正如你所使用的jQuery你可以這樣做:

if (jQuery.inArray(val,validAr)==-1) 
{ 
    alert('Invalid'); 
} 
相關問題