Rule definition

In React Advanced Form writing validation rules is about declaring resolver functions and applying them to a define set of fields.

Resolver

Resolver is a function that returns the next validity of the associated field.

Resolver is explicitly analyzed aside from the rest of validation context because it is a single independent unit of validation, and should be treated as such during the composition of a validation schema.

Definition

type RuleResolver = (params) => boolean

Parameters

Parameter name

Type

Description

get

Function

Reactive props getter function.

value

any

The value of a field.

fieldProps

Object

Props of a field.

form

Object

Form component reference.

Resolver example

/**
 * A simple resolver that takes the value of a field
 * and resolves when it is more than 6 characters long.
 */
const validatePassword = ({ get, value, fieldProps, form }) => {
  return value.length > 6
}

It is a good practice to write high-order resolvers. Favor functional composition.

Selector

Selector is a key path of [propName, propValue] that defines the application scope of a single or multiple validation resolvers. Think of it as a CSS selector, that controls which elements (fields) are effected by the specified rules (validation). The following selectors are supported:

  • type — selects fields by their type,

  • name — selects fields by their name.

  • fieldGroup — selects the fields under the specified field group path.

Priority

Selectors are executed in a certain order (from highest to lowest):

  1. name[fieldName] / name[fieldName][ruleName]

  2. type[fieldType] / type[fieldType][ruleName]

Example

Multiple resolvers

Each field selector can have multiple resolvers applied in parallel by accepting an Object of the shape {[ruleName: string]: RuleResolver} as its value.

Having unique rule names allows to associate the rule with its validation message. Using example above, we can have different error messages for capitalLetter and oneNumber rules.

Read more on that.

Grouped fields

Apart from less specific selectors (type/name), it is also possible to select fields based on their field group(s). Include the field groups key path in the schema as a value of the fieldGroup key:

Learn more about Field grouping.

Last updated