logo dile-components dile-components

Validation in the CRUD

The @dile/crud components validate their forms before sending them to the server. They call the validate() method of the form, so any form with the DileForm mixin is validated with no extra code: required fields and the fields' own errors. Add the DileFormValidation mixin to the form to use rules.

Which components validate

Use the skipValidation property of dile-ajax-form or of a step of dile-steps-form to send the data without validating.

Rules in the resource configuration

With the full dile-crud or dile-crud-single, declare the rules in the validation property of the resource configuration. It is useful when the insert and update operations share the same form but need different rules:

validation: {
  insert: {
    name: 'required|maxLength:80',
    password: 'required|minLength:8',
  },
  update: {
    name: 'required|maxLength:80',
    password: 'minLength:8',
  },
  actions: {
    ChangeNameAction: { name: 'required|minLength:3' },
  },
  messages: {
    minLength: 'Write at least {min} characters',
  },
}

The CRUD hands each schema to its form with setValidationSchema(schema, { operation, messages }), so it takes precedence over the static validations of the form class and the validations attributes of the fields. The forms must apply the DileFormValidation mixin, otherwise the rules are ignored and a warning is logged in the console.

The standalone components take the same rules in their own properties: validationSchema and validationMessages in dile-ajax-form, dile-crud-insert and dile-crud-update, and validationSchemas (by action name) in dile-crud-actions.

Operations of type handler (insertOperation, updateOperation) get no validation rules: a handler is your own code, so whether and how it validates on the client is up to you.

Declare the rules in one place for each project: in the resource configuration when you use the full dile-crud, or in the form (static validations or attributes) when you use standalone forms.

Server errors

The server keeps validating the data. Its errors are shown in the fields as usual: dile-ajax-form flattens the arrays of messages of the response ({ name: ['msg1', 'msg2'] }) to the same { field: message } shape of the client errors, reveals the fields inside closed containers and focuses the first one. See the save-error event of dile-ajax-form.

With live validation, a server error disappears when the user changes the value and the new value passes the client rules (see Live validation).

Language

The CRUD components hand their language to the form, so the live validation and the validation before sending use the same language. See Messages and languages.

Demos

The repository includes a complete demo of dile-steps-form with an in-memory API and validation errors. The pages of dile-ajax-form and the CRUD component have live demos.