我将此脚本添加到jsp文件中。

即使对于失败的情况(例如不匹配表达式和所有内容),此函数始终返回true。

为什么会这样呢?如何解决呢?

<script type="text/javascript">
function validate()
{
    document.getElementById("user").innerHTML="";
    document.getElementById("pass").innerHTML="";
    document.getElementById("mail").innerHTML="";
    document.getElementById("number").innerHTML="";

    var expression = /^[a-zA-Z_.0-9]+$/;
    var mailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}+$/;
    var numberExp = /^[0-9]+$/;
    if(!document.getElementById('username').value.match(expression))
    {
        document.getElementById('username').focus();
        document.getElementById("user").innerHTML=" Enter valid user name";
        return false;
    }
    if(document.getElementById('password').value.length == 0)
    {
        document.getElementById('password').focus();
        document.getElementById("pass").innerHTML = "Fill Password field";
        document.getElementById("pass").style.visibility = "visible";
        return false;
    }
    if(document.getElementById('cnfpassword').value.length == 0)
    {
        document.getElementById('cnfpassword').focus();
        document.getElementById("pass").innerHTML = "Fill confirm Password field";
        document.getElementById("pass").style.visibility = "visible";
        return false;
    }
    if(document.getElementById('password').value != document.getElementById('cnfpassword').value)
    {
        document.getElementById('password').focus();
        document.getElementById("pass").innerHTML = "Password and confirm password Not match";
        document.getElementById("pass").style.visibility = "visible";
        return false;
    }
    if(!document.getElementById('emailid').value.match(expression))
    {
        document.getElementById('emailid').focus();
        document.getElementById("mail").innerHTML=" Enter valid E-mailID";
        document.getElementById("mail").style.visibility = "visible";
        return false;
    }
    if(!document.getElementById('number').value.match(numberExp))
    {
        document.getElementById('number').focus();
        document.getElementById("number").innerHTML=" Enter only numbers";
        document.getElementById("number").style.visibility = "visible";
        return false;
    }
    else
    {
        return true;
    }
 }

最佳答案

除了重构建议外,最简单的方法是使用Firebug并调试出问题所在。它将使您免于头痛

关于javascript - 错误:JavaScript始终返回true,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6621631/

10-10 22:22