Set validation action for required fields in html-form

Although the answer by Raul Marquez is working, I want to share my own solution:

<!DOCTYPE html>
<html lang='en'>
<head>
    <title>Test</title>
</head>
<body>
    <div class='inner'>
        <form method='POST' action='php/send.php' class='input'>
            <label>Your Name:</label><br>
            <input class='validInput' type='text' name='myName' placeholder='Name' required/><br><br>
            <label>Your Email:</label><br>
            <input class='validInput' type='email' name='myEmail' placeholder='E-Mail' required/><br><br>

            <label>Message:</label><br>
            <textarea class='validInput' rows='8' name='myMessage' id='myMessage' placeholder='Message' required></textarea><br><br>
            <input class='validInput' type='submit' value='Send'/>
        </form>
    </div>
    <script>
        //Get an array of elements with classname 'validInput'
        let elements = document.getElementsByClassName('validInput');

        //iterate over the elements
        for(let i = 0; i < elements.length; i++) {

            //When user focuses on one element (clicks on that element and writes something)
            elements[i].addEventListener('focus', function() {
                this.style.border = '3px solid green';
            });

            //When user stops focusing on an element
            elements[i].addEventListener('blur', function() {
                this.style.border = '1px solid #f3f3f3';
            });

            //When user submits the form and the field-value is invalid
            elements[i].addEventListener('invalid', function(event) {
                event.preventDefault();
                this.style.border = '3px solid red';
            });
        }
    </script>
</body>
</html>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top