Skip to main content

Rules

When a form becomes complex, it often happens that we want to apply a business logic when the value of a field changes \ To achieve that, Oneki.js provides:

  • several methods to interact with a field
    • to update its value.
    • to set its status (error, warning, ok, pendingValidation)
  • a hook to implement the business logic (= rule)

Methods to interact with a field

useForm (or useFormContext() if inside a custom form component) provides several methods to interact with a field:

import { useForm } from "onekijs";

const {
setValue,
setPendingValidation,
setError,
setWarning,
setOK,
} = useForm();

ParameterTypeDescription
setValue(fieldName: string, value: any): voidSet the value of a field. Generally used within a rule
Example: setValue('lastname', 'Doe')
setPendingValidation(fieldName: string, validatorName: string, pending?: any): booleanMark a field as pending validations. Generally used within a rule. Check the Validations section for more details
Example: setPendingValidation('password', 'complexity')
setError(fieldName: string, validatorName: string, message?: string, match?: boolean): booleanMark a field in error. Generally used within a rule. Check the Validations section for more details.
Example: setError('password', 'complexity', 'Password is too weak', password.length < 6)
setWarning(fieldName: string, validatorName: string, message?: string, match?: boolean): booleanMark a field in warning. Generally used with rule. Check the Validations section for more details.
Example: setWarning('password', 'complexity', 'Password is weak', password.length < 8)
setOK(fieldName: string, validatorName: string): booleanMark a field as OK. Generally used within a rule. Check the Validations section for more details
Example: setOK('password', 'complexity')

Rule

If often happens that a change of a field triggers an update of another field (check the complex validation example)
The framework provides the useRule to achieve this.

useRule(rule, observed);

Input

ParameterTypeDescription
rule*RuleA synchronous or asynchronous function that receive as arguments the observed field values. Example: (password: string, confirmPassword: string) => setError('confirmPassword', 'password-match-validator', "Passwords don't match", password !== confirmPassword)
observedany[]A array of fieldnames observed by the binder. You must use useValue to react of these fields
Example:: [useValue('password'), useValue('confirmPassword')]

Output

No output

Example

Minimal rule example

import { useRule, useValue } from "onekijs";

const { setError } = useForm();

useRule(
async (username) => {
const user = await asyncGet("/users/username");
setError(
"username",
"unique-validator",
`Username ${username} is already taken`,
user !== null
);
},
[useValue("username")]
);

Full example

examples/cra-form-basic/src/pages/rules.tsx
loading...