Skip to main content

Showing validation errors

When wrapping form controls in <inform-field/>, validation errors are automatically displayed:

  • When attempting to submit the form
  • Or when the field has been "touched"

This means that errors are not shown when initially loading the form even if some fields are invalid (for example when using the required attribute). Errors are shown for a field after the user modifies it for the first time, or when trying to submit.

See the example below:

<inform-el>
<form>
<label>
First Name
<inform-field>
<input type="text" name="firstName" required />
</inform-field>
</label>
<label>
Last Name
<inform-field>
<input type="text" name="lastName" required minlength="2" />
</inform-field>
</label>
<button type="submit">Submit</button>
</form>
</inform-el>

Try submitting the empty form below to see the errors:

informel leverages native form validation features and displays native validation messages by default.

Customizing errors​

CSS variables​

It is possible to style the errors shown by <inform-field /> by using the following CSS variables:

  • --error-color: Color of the error text. Default: red. Accepts any valid value for CSS color: property.
  • --error-margin: Margin of the error text. Default: 0 0 0 0. Accepts any valid value for CSS margin: property.
  • --error-font-size: Font size of the error text. Default: 1rem. Accepts any valid value for CSS font-size: property.
  • --error-font-family: Font size of the error text. Default: inherit. Accepts any valid value for CSS font-family: property.
  • --error-display: Font size of the error text. Default: block. Accepts any valid value for CSS display: property.

It is possilbe to set those CSS variable, either globally on <inform-el /> (applies to all fields), or individually on a <inform-field /> element.

Example:

inform-el {
--error-color: blue;
--error-margin: 0 0 0 10px;
--error-display: inline-block;
--error-font-size: 0.75rem;
--error-font-family: 'courier new';
}

Custom error slot​

It is also possible to come with your own DOM element for showing the error, by providing an error slot:

<inform-field>
<input type="text" name="firstName" placeholder="First name" required />
<span slot="error" role="alert" />
</inform-field>

Outlining fields in error​

A common way of outlining the field in error is using the :invalid selector:

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

The main issue with that is that fields can already be invalid when the form is first loaded. So <input type="text" required /> would display the red border before the user had a chance to enter anything, which is not very nice.

<inform-field/> only shows errors when the field has been touched (blurred) at least once and it has a error attribute set when the error is shown. So the example above would become:

inform-field[error] input {
border: 1px solid red;
}