javascript表单验证文本字段长度

时间:2013-08-20 10:40:19

标签: javascript validation

我在验证学生ID方面遇到了问题,它需要10个号码,我遇到的问题是当我输入有效的学生证时,它仍然返回false。请帮我检查一下我的编码,非常感谢你。

我的学生证的例子=“1101106363”

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

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

5 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:1)

这里有些奇怪的事。 您正在检查该值是否为空,或者它是否为数字(如果值不是数字,则isNaN返回true;如果放置,则isNaN返回!isNaN如果值为数字,则结果为true),或者如果长度较差到了11。

如果你想确定插入的值不是null,一个数字及其长度低于11你应该写

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

答案 2 :(得分: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;
}

答案 3 :(得分: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;
    }

答案 4 :(得分:0)

你的if语句会捕获长度小于或等于10的学生ID。

测试长度如10而不是