2013-08-20 132 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而不是