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'>
    <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>

            <textarea class='validInput' rows='8' name='myMessage' id='myMessage' placeholder='Message' required></textarea><br><br>
            <input class='validInput' type='submit' value='Send'/>
        //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() {
       = '3px solid green';

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

            //When user submits the form and the field-value is invalid
            elements[i].addEventListener('invalid', function(event) {
       = '3px solid red';

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top