Form validation

You should always validate data on your server. But validating the data before the user gets to send it ensures that the data sent is what you're asking for, and can handle. Also, it gives the user feedback earlier that they need to fix something with their input.

By using the correct type attribute, the form will not be validated before the user have fulfilled the requirement for that attribute (e.g. the value of an input element with the type attribute set to the value email must be a legal e-mail address).

To help the user see where the error have been made, you can use the CSS pseudo-classes :invalid and :valid.

HTML

<form>
    <label for="email">E-mail:</label>
    <input type="email" id="email" name="email" required>
    <button>Submit</button>
</form>

CSS

input:invalid{
    border: 1px solid red;
}

input:valid{
    border: 1px solid green;
}

In the above example you can see that the required attribute is present. This ensures that the form can't be submitted until that input element have a value. If the input element have no value, the user will be prompted by a message stating that it needs a value. pattern, maxlength, min and max can also be used to validate the content of an input element.

Last updated