---
tags: zeta-dom-react
---
# Form validation
## Adding validation to field
Field validations are accomplished by `onValidate` callback which returns:
- A falsy value, i.e. empty string, `null` or `undefined` if valid
- A non-empty string containing error message if invalid
For example sample validaton would be:
```typescript
<TextField name="item"
onValidate={value => value.length > 10 ? '' : 'Too short'} />
```
Again the `onValidate` callback support async operation:
```typescript
<TextField name="item"
onValidate={async (value) => await asyncValidation(value) ? '' : 'Error'} />
```
:::info
For more complex scenario or reuse of validating function, see [Validators](/MqseTJw2RvyBFND7iITRFw).
:::
## Triggering validation
### Validate on change
Field can be automatically validated upon changes.
The `validateOnChange` option can be set to `FormContext` or to each field, where the field setting overrides form setting.
By default, `validateOnChange` is on for a form context.
### Manually triggering validation
Validations can be triggered by calling `form.validate()`.
It returns a promise which resolves to `true` if all fields are valid.
The async nature of `form.validate()` allows server validations.
```typescript
function Component() {
const form = useFormContext();
return (
<Form context={form}>
<TextField name="item" required={true} />
<button onClick={async () => await form.validate() && doStuff(form.data.item)} />
</Form>
);
}
```
The `form.validate` can also validates specified fields:
```typescript
await form.validate('item1', 'item2');
```
## Validation event
```typescript!
useEffect(() => {
return form.on('validateChange', e => {
if (e.name === 'input') {
// gets whether the field is valid after validation
console.log(e.isValid);
}
});
}, [form]);
```