skip to Main Content

When I press the submit button for an empty HTML text input, this default message automatically appears. I want the border of the box to become red instead of this default message appearing. How do I do it?

Here’s the code for the box:

<div class="input-group" id="email-input">
  <input type="text" id="email" name="email" autocomplete="off" required placeholder="Email">
</div>

Screenshot showing the default message

2

Answers


  1. You can use novalidate attribute for form, but it will be works the same way as non-required(your required will be ignored)

    <form onsubmit="return false" id="form" novalidate>
      <div class="input-group" id="email-input">
       <input type="text" id="email" name="email" autocomplete="off" required placeholder="Email">
      </div>
      <div>
        <input type="submit" value="Submit form" />
      </div>
    </form>
    Login or Signup to reply.
  2. We can do this by using JavaScript, there is a event called invalid that fires on every error. We will use that event and check by regex if text is proper email or not. We will create a function for this.

    Here’s the code:

    HTML

    <input type="email" id="input" required>
    

    JavaScript

    const input = document.querySelector('#input');
      
    function validation(elem) {
        elem.addEventListener('invalid', function (event) {
            event.preventDefault();
            if (elem.value === '') {
                alert("Fill Your Email");
            } else if (!/^[^s@]+@[^s@]+.[^s@]+$/.test(elem.value)) {
                alert('Invalid Email');
            } 
        });
    }
    
    validation(input);
    

    Note : This currently only supports validation of Email inputs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search