如何使用Javascript和html验证Cconfirm密码

时间:2017-02-24 05:55:06

标签: javascript html validation

我正在尝试验证密码并使用javascript确认密码但不能正常工作,这是我的代码可以告诉任何人什么错误吗?

    <html>
<head>
</head>
<body>
<script type="text/javascript">
    function validateForm() {
    var pass,cpass;
    pass= document.getElementByName("password")[0].value;
    cpass= document.getElementByName("cpassword")[0].value;   
         if(pass!=cpass){
        alert("Password And Confirm Password Should Be Same");
        return false;
      }
    }
</script>
<form name="form1" onsubmit="return validateForm()">
<label>Password     : </label><input class="ip1" type="password" name="password" required/>
<label>Confirm Password     : </label><input class="ip1" type="password" name="cpassword" required/>
<input type="submit" value="submit"/>
</form>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您错误输入了getElementByName,它应该是getElementsByName

<html>
<head>
</head>
<body>
<script type="text/javascript">
    function validateForm() {
        var pass,cpass;
        pass  = document.getElementsByName("password")[0].value;
        cpass = document.getElementsByName("cpassword")[0].value;

        if(pass!=cpass){
            alert("Password And Confirm Password Should Be Same");
            return false;
        }
    }
</script>
<form name="form1" onsubmit="return validateForm()">
    <label>Password     : </label><input class="ip1" type="password" name="password" required/>
    <label>Confirm Password     : </label><input class="ip1" type="password" name="cpassword" required/>
    <input type="submit" value="submit"/>
</form>

</body>
</html>