Skip to content
Advertisement

How to validate with both html pattern and a script?

I have an html form and a script, validate.js, which runs after a submit button is clicked to check if given passwords are the same. Form’s inputs fields also have pattern attributes for validation. The problem is, whenever the button is clicked, the script is executed and there is no html pattern validation. Only validation from script occurs.

Here is the 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>

and 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();
    }
}

Why pattern validation does not work? What is wrong with this code?

Advertisement

Answer

The problem is on your javascript. You’ve submitted the form directly via javascript thus bypassing the behavior of html form for checking first the pattern before submitting. To correct it just put a hidden submit button. Then trigger that button via javascript. See script below.

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>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement