Skip to main content

useForm

The useForm hook is the starting point for creating a new form. This hook provides

  • a <Form/> component to encapsulate all controlled fields
  • several helpers methods to control the form

The <Form/> component has two main roles

  • it handles the submit action
  • it provides a context to sub components
import { Form } from "onekijs"; // or from onekijs-next

export const MyForm = () => {
const { Form } = useForm((values) => console.log(values));

return (
<Form>
<div>
<b>Name: </b>
<Input name="lastname" />
</div>
<button type="submit">Submit</button>
</Form>
);
};

Signature

const {
// High level API
field,
Form,
setError,
setValue,
setOK,
setWarning,
setPendingValidation,
validation,
value,

// Low level API
clearValidation,
setValidation,
submit,
validations,
values,
} = useForm(submit, options);

Inputs

ParameterTypeDescription
submit*FormSubmitCallbackA function called when the user clicks on the submit button. The function receives the content of the form (= values) as parameter.
Example: a function that performs a AJAX POST request
optionsFormOptionsAn object that contains optional options
initialValuesobjectInitial value of the form.
Example: if the form is used to edit a user, initialValues would be a JSON object that represents the user before editing.

Defaults to: {}
touchOnTouchOnTypeIndicates which event marks the field as touched.
The validations of a field are performed as soon as it has been touched.

Valid values are
- blur: when the field is exited
- change: when the content of the field is changed
- focus: when the field is entered
- load: when the field is loaded
- submit: when the form is submitted.

Defaults to: blur
onErrorFormErrorCallbackA function called when the submit button is pressed and there are still fields in error

Signature: onError(fields, values)
- fields: fields in error (key = fieldName, value = validation object)
- values: the full value of the form

Defaults to: No error callback called
onWarningFormWarningCallbackA function called when the submit button is pressed and there are still fields in warning

Signature: onWarning(fields, formValue)
- fields: fields in warning (key = fieldName, value = validation object)
- formValue: the full value of the form

Defaults to: No warning callback called

Outputs

useForm returns an object of type UseForm that contains the following attributes:

ParameterTypeDescription
field(name: String, validators?: Validator[], options?: FieldOptions): FieldPropsRegister a field as a controlled element. Check the Field section for more details
Example: field('lastname', [required()])
FormFC<FormProps>Component that wraps all the controlled fields. It handles the submit action.
Example: <Form><Input name="lastname" /></Form>
getValue<T>(fieldName: string): T | undefinedA helper to get the value of a field. Returns undefined if the value is not initialized. Check the Field section for more details
Example: getValue('address.street')
getValidation(fieldName?: string, touchedOnly?: boolean): ContainerValidation | FieldValidationA helper to get the validation of a field. Returns { status: null, message: null } if the validation is not initialized. Check the Field section for more details
Example: getValidation('address.street').status
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)
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')
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)
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')
setValue(fieldName: string, value: any): voidSet the value of a field. Generally used within a rule
Example: setValue('lastname', 'Doe')

The following attributes are also part of UseForm, but are considered as low-level APIs

ParameterTypeDescription
clearValidation(fieldName: string, validatorName: string, code: ValidationCode): voidRemove a validation from a field. Check the Validations section for more details
Example: clearValidation('lastname', 'required', ERROR)`
setValidation(fieldName: string, validatorName: string, code: ValidationCode, message?: string): voidAdd a validation to a field. Check the Validations section for more details
Example: setValidation('lastname', 'required', ERROR, 'Lastname cannot be empty')
submit(e?: SyntheticEvent<Element, Event>): voidThe submit method used to execute all validations, gather the content of the form and call the user-submit method
Low level API, generally hidden by the Form component
Example: submit()
valuesanyThe full content of the form
It's preferable to use getValue instead of values to avoid having to handle undefined values
Example: values.address.street
validationsAnonymousObject<FieldValidation>All field validations of the form (even of non-touched fields)
It's preferable to use getValidation instead of validations because it takes care of the touch status and return { message:null, status:null } if the validation has not been yet initialized
Example: validations['address.street'].status

Example

Minimal example

export const MyForm = () => {
// useForm expects a "submit" method called when the
// user clicks on the submit button
const { Form } = useForm((values) => console.log(values));

return (
<Form>
<div>
<b>Name: </b>
<Input name="lastname" />
</div>
<button type="submit">Submit</button>
</Form>
);
};

Example with validations

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