Alex Ruehlicke
Alex Ruehlicke

Reputation: 1

JS external file password validation

I am having trouble running a program to validate correct passwords. I have a form with two text fields, one is ‘password’ and the other is ‘password 2’ with an external Java script file. I have a function that validates them. I’m not sure how to connect my files along with calling the function.

When I test it, I put in the wrong password but the form still submits with incorrect information and doesn’t display the error message I wrote.

Any help is appreciated.

Upvotes: 0

Views: 281

Answers (1)

A.DUPONCHEL
A.DUPONCHEL

Reputation: 193

You can add a listener function to the 'submit' event from your form. Your function will receive a Event from which you can get your form using e.currentTarget

Finally don't forget to call e.preventDefault() to cancel the form submission

<body>
    <form id="js-form">
        <input type="text" name="password"/>
        <input type="text" name="password2"/>
        <input type="submit" value="submit"/>
    </form>
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            document.getElementById("js-form").addEventListener('submit', (e) => {
                const $form = e.currentTarget;
                if($form['password'].value !== $form['password2'].value) {
                    alert('password mismatch');
                    e.preventDefault();
                }
             });
        }); 
    </script>
</body>

Upvotes: 1

Related Questions