javascript setCustomValidity不起作用

时间:2016-04-19 13:44:42

标签: javascript

我是Javascript的新手,我想检查输入两次的密码是否使用Javascript匹配。但它似乎不起作用:

<html>
<head>
<script>
function checkpasswd(){
    var p1 = getElementById("password1");
    var p2 = getElementById("password2");
    if( p1.value != p2.value){
        p2.setCustomValidity("passwd don't match");
    }else{
        p2.setCustomValidity("");
    }
}
</script>
</head>

<body>
    <form>
    passwd:<input type="password" name="password1" id="password1">
    confirm passwd:<input type="password" name="password2" id="password2" onchange="checkpasswd()">
    </form>
</body>
</html>

3 个答案:

答案 0 :(得分:4)

使用 document.getElementById()并使用正确的 ID

function checkpasswd(){
    var p1 = document.getElementById("password1");
    var p2 = document.getElementById("password2");
    if( p1.value != p2.value){
        p2.setCustomValidity("passwd don't match");
    }else{
        p2.setCustomValidity("");
    }
}

答案 1 :(得分:0)

我已编辑了您的代码

<html>
<head>
<script>
function checkpasswd(){
    var p1 = document.getElementById("password1");
    var p2 = document.getElementById("password2");
    var result = document.getElementById("result");
    if( p1.value != p2.value){
        result.innerHTML = "passwd don't match";
        p2.setCustomValidity("passwd don't match");
    }else{
        result.innerHTML = "passwd  match";
        p2.setCustomValidity("");
    }
}
</script>
</head>

<body>
    <form>
    passwd:<input type="password" name="password1" id="password1">
    confirm passwd:<input type="password" name="password2" id="password2" onkeyup="checkpasswd()">
    </form>

    <div id="result"></div>
</body>
</html>

答案 2 :(得分:0)

用于查找元素的id名称拼写错误。你需要提到正确的ID来获得元素。

您忘记使用文档对象,并直接尝试访问getElementById。

<html>
<head>
<script>
function checkpasswd(){
    var p1 = document.getElementById("password1");
    var p2 = document.getElementById("password2");
    if( p1.value !== p2.value){
        p2.setCustomValidity("passwd don't match");
    }else{
        p2.setCustomValidity("");
    }
}
</script>
</head>

<body>
    <form>
    passwd:<input type="password" name="password1" id="password1">
    confirm passwd:<input type="password" name="password2" id="password2" onchange="checkpasswd()">
    </form>
</body>
</html>