简体   繁体   中英

javascript setCustomValidity doesn't work

I am new to Javascript,I wanna check if the passwords typing two times are matched using Javascript. But it seems doesn't work:

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

Use document.getElementById() and use the right 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("");
    }
}

i have edited your code

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

The id name u are using to find an element is misspelled. You need to mention the correct ID to get the element.

You forgot to use document object, and directly trying to access 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM