Search code examples
htmlformsvalidationemailsass

CSS code for changing appearance of an email form element if format is not valid


I want to change the appearance of this email form element when the inserted email address does not match the pattern which I stated, but I am not sure what to use, I tried using :invalid but I'm not sure if it works or not, so I would like to hear from you guys.

The code is:

<input type="email" name="email" required placeholder="Your Email" pattern="[a-zA-Z1-9]+@[a-zA-Z1-9]+\.[a-zA-Z]{2,}"/>
        [type="email"]{
            padding:.7rem;
            border-radius:.3rem;
            border:none;
            margin-right:2rem;

            &:invalid{
                outline:none;
                border:1px solid red;
            } 
        }

Solution

  • Except for the pattern everything is alright and works. You can test it here:

    [type="email"] {
      padding: .7rem;
      border-radius: .3rem;
      border: 1px solid gray;
      margin-right: 2rem;
    }
    
    [type="email"]:invalid {
      border: 1px solid red;
    }
    <label>Your Email
      <input type="email" name="email" required placeholder="[email protected]" />
    </label>

    Not showing errors on empty inputs

    It‘s not a good practice to greet the user with a bunch of errors before they entered any data.

    Bootstrap uses a .was-validated class on the <form>, to hide the error states until that class was added via JavaScript.

    .was-validated input:invalid
    

    Another solution without CSS might be the use of the :placeholder-shown pseudo-class to hide the error state.

    This needs a placeholder attribute, which can be set to placeholder="".

    input:invalid:not(:placeholder-shown) {
      border-color: red;
    }
    
    /* or, backwards-compatible */
    input:invalid {
      border-color: red;
    }
    
    input:placeholder-shown {
      border-color: initial;
    }
    <label>Your Email
      <input type="email" name="email" required placeholder="[email protected]" />
    </label>

    Beware of restrictive patterns/regex

    You should not provide yet another pattern for validation. The browser already has a pattern implemented based on tons of research and with the help of a lot of engineers.

    See How can I validate an email address in JavaScript? for some ideas on what you are missing.

    I find it important to point this out, as restricting input data is effectively discriminating against users who’s data patterns were missed in the design. This is especially true for groups who are underrepresented in engineering staff.