Skip to main content

Validation rules & error messages

Custom validation rules​

informel uses the browser built-in form validation by default, with attributes such as required, minlength, pattern, type="email", type="url" etc...

Here is an example (try submitting the form):



On top of that, it is possible to specify custom validation rules, via the `validationHandler` property:
document.querySelector('inform-el').validationHandler = ({ values }) => {
// Returns an object {'field name': 'error message'}
};

Custom error message​

When a field is in error, the control's validationMessage is shown by default.

For example, on Google Chrome, <input type="text" required /> will show Please fill out this field. while <input type="checkbox" required /> will show Please check this box if you want to proceed..

To customize this behavior, you can either use validationHandler as shown above, or use the following attributes on <inform-field />:

  • default-error: a fixed error message displayed whenever the field is in error (regardless of the reason).
  • For each property in the native ValidityState object, <inform-field /> accepts a corresponding kebab-case attribute to specify the error message. For example, if the field is <input type="email" required /> and you want to show different errors when the value is not set or when the value doesn't have the right format, you can use the value-missing and the type-mismatch attributes. See them in action here:

When multiple errors are specified, the order of precedence is:

  1. Error returned by validationHandler
  2. <inform-field /> ValidityState attribute
  3. <inform-field /> "default-error" attribute
  4. The element native validationMessage.

Using zod for validation​

A zod schema can be specified via the zodSchema property:

document.querySelector('inform-el').zodSchema = z.object({
first_name: z.string().min(1, { message: "Firstname is required" }),
last_name: z.string().min(1, { message: "Lastname is required" }),
email: z.string().min(1, { message: "Email is required" }).email({
message: "Must be a valid email",
}),
password: z
.string()
.min(6, { message: "Password must be atleast 6 characters" }),
terms: z.literal(true, {
errorMap: () => ({ message: "You must accept Terms and Conditions" }),
}),
});

Just like other validation methods, if the form values are incompatible with the schema, errors are shown and submission is blocked.

Disabling the submit button on error​

When adding the error-disable-submit attribute on <inform-el />, the submit button is automatically disabled while errors are shown: