如何同时使用HTML模式和脚本进行验证?

时间:2018-10-24 23:10:37

标签: javascript html

我有一个html表单和一个脚本validate.js,该脚本在单击提交按钮以检查给定的密码是否相同后运行。表单的输入字段还具有用于验证的模式属性。问题是,每当单击按钮时,脚本都会执行,并且没有html模式验证。仅通过脚本进行验证。

这是html:

<form id="submitForm" method="post" action="register.php" name="registerform">
    <input type="name" name="user_name" id="inputName" pattern="somePattern">
    <input type="password" name="user_password" id="password" pattern="somePattern">
    <input type="password" id="repeatPassword" >

    <p id="errorMessage"><p>

    <button type="button" id="submitButton">Register</button>
</form>

和validate.js:

document.getElementById('submitButton').onclick = function () {
    var password = document.getElementById('password').value;
    var repeatPassword = document.getElementById('repeatPassword').value;
    if (password !== repeatPassword) {
    document.getElementById('errorMessage').innerHTML = 'Passwords have to be the same!'
    } else {
        document.getElementById('submitForm').submit();
    }
}

为什么模式验证无效?此代码有什么问题?

1 个答案:

答案 0 :(得分:1)

问题出在您的JavaScript上。您已经直接通过javascript提交了表单,因此绕过了html表单的行为,以便在提交之前先检查模式。要纠正它,只需放置一个隐藏的提交按钮。然后通过javascript触发该按钮。参见下面的脚本。

document.getElementById('submitButton').onclick = function () {
    var password = document.getElementById('password').value;
    var repeatPassword = document.getElementById('repeatPassword').value;
    if (password !== repeatPassword) {
    document.getElementById('errorMessage').innerHTML = 'Passwords have to be the same!'
    } else {
        //document.getElementById('submitForm').submit();
        document.getElementById("hiddenSubmit").click();
    }
}
<form id="submitForm" method="post" name="registerform">
    <input type="name" name="user_name" id="inputName" pattern="[A-Za-z]{3}">
    <input type="password" name="user_password" id="password">
    <input type="password" id="repeatPassword" >
	
    <p id="errorMessage"><p>
	<input type="submit" style="display:none;" id="hiddenSubmit">
    <button type="button" id="submitButton">Register</button>
</form>