2013-08-20 48 views
0

我在驗證學生ID時遇到了問題,它需要10個數字,我遇到的問題是當我鍵入有效的學生ID時,它仍然返回false。請幫我檢查一下mycoding,非常感謝。我的學生ID = 「1101106363」 的JavaScript表單驗證textfield長度

例如

if ((document.appsub.id.value == "") || !(isNaN(document.appsub.id.value)) || (document.appsub.id.value.length < 11)) 
    { 
     alert("Please enter the correct Student ID"); 
     document.appsub.id.focus(); 
     return false; 
    } 

更新:[鏈接] http://jsfiddle.net/rVswq/1/

+1

您選擇用於訪問文檔元素的方法不是最新的,對於所有瀏覽器都不安全。您應該使用像'的document.getElementById()'來替代,或者'document.getElementsByTagName()'如果你想元素的數組上工作。爲了使自己的生活更輕鬆考慮讓自己熟悉jQuery。它會簡化你的生活! – cars10m

+0

@ cars10試過了,可以指我哪裏錯了,謝謝[鏈接] jsfiddle.net/rVswq/1/ –

+1

看看這個http://jsfiddle.net/rVswq/3/。你在if子句中使用括號犯了一個錯誤,並且'id.innerHTML.length'錯誤 - >'id.value.length'。 – cars10m

回答

2

您需要使用document.getElementById方法正確選擇元素。

 
var el = document.getElementById("yourid"); 
if (!(isNaN(el.value)) || (el.value.length < 11)) 
    { 
     alert("Please enter the correct Student ID"); 
     el.focus(); 
     return false; 
    } 
+0

...當然沒有在'isNaN'前面的'!'操作... ;-) – cars10m

+0

其實你不這樣做,但這是更好練習跨瀏覽器的兼容性 – geedubb

+0

我知道他的代碼有點奇怪,所以我只是把正確的方式在那裏 – woofmeow

0

它看起來像你對我不需要NOT操作

if ((document.appsub.id.value == "") || isNaN(document.appsub.id.value) || (document.appsub.id.value.length < 11)) 
{ 
    alert("Please enter the correct Student ID"); 
    document.appsub.id.focus(); 
    return false; 
} 
0

你的IF聲明是錯誤的。你想:

if ((document.appsub.id.value == "") || (isNaN(document.appsub.id.value)) || document.appsub.id.value.length < 11)) 
    { 
     alert("Please enter the correct Student ID"); 
     document.appsub.id.focus(); 
     return false; 
    } 
1

這裏有一些奇怪的東西。 要檢查,如果該值爲null,或者如果它是一個數字(如果該值不是一個數字isNaN返回true,如果你把!isNaN結果爲真,如果該值是一個數字),或者如果長度不如11

如果你想確保插入的值不爲空,一個數字,它的長度不如11,你應該寫

if ((document.appsub.id.value == "") || isNaN(parseInt(document.appsub.id.value)) || (document.appsub.id.value.length > 10)) 
0

你的if語句將趕上長度爲學生IDS少等於或等於10.

測試長度爲10而不是