使用JavaScript输入字段进行验证无法验证这两个字段

时间:2015-08-23 16:32:11

标签: javascript

当我在输入字段中输入错误的输入时,它仅验证第一个字段并显示消息,但无法验证第二个字段。

我该如何解决这个问题?

我的代码

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Form_Valid_JS</title>

</head>

<body>
<form name="form">
    <label style="font-size:18px"><strong> Name</strong> </label><br><br>
    <input type="text" id="lname" name="lname" placeholder="First Name" pattern="[a-zA-Z\s]{0,10}" onBlur="lvalidity()">
    <input type="text" id="fname" name="fname" placeholder="Last Name" pattern="[a-zA-Z\s]{0,10}" onBlur="validity()">

    <p id="fnamee"></p> <br>

    <p id="lnamee"></p>

    <input type="submit">
</form>
</body>
</html>
<script>
    function validity() {
        var txt = "";
        if (document.getElementById("fname").validity.patternMismatch) {
            txt = " *Plz write only alphabet with maximum 10 Characters.";
        }
        document.getElementById("fnamee").innerHTML = txt;
    }
    function lvalidity() {
        var txt = "";
        if (document.getElementById("lname").validity.patternMismatch) {
            txt = " *Plz write only alphabet with maximum 10 Characters.";
        }
        document.getElementById("lnamee").innerHTML = txt;
    }

</script>

1 个答案:

答案 0 :(得分:0)

onBlur中,您可以访问输入文本字段的ValidityState,该字段也会被命名为validity,并覆盖您的function validity()

function validity()
{
    var txt="";                       // this thing here
                                      //   |
                                      //   |
                                      //   v
    if( document.getElementById("fname").validity.patternMismatch)
    {
        txt=" *Plz write only alphabet with maximum 10 Characters.";
    }
    document.getElementById("fnamee").innerHTML=txt;
}

解决方案是将函数validity重命名为其他内容。