diff --git a/docs/reference/classes/formapi.md b/docs/reference/classes/formapi.md index 2b6275dba..05355f9b4 100644 --- a/docs/reference/classes/formapi.md +++ b/docs/reference/classes/formapi.md @@ -746,3 +746,37 @@ Validates a specified field in the form using the correct handlers for a given v \| [`ValidationError`](../type-aliases/validationerror.md)[] \| `Promise`\<[`ValidationError`](../type-aliases/validationerror.md)[]\> + +*** + +### validateFields() + +```ts +validateFields(fields: DeepKeys[], cause): Promise +``` + +Defined in: [packages/form-core/src/FormApi.ts:797](https://github.com/TanStack/form/blob/main/packages/form-core/src/FormApi.ts#L797) + +Validates an array of fields in the form using the correct handlers for a given validation type. + +#### Type Parameters + +• **TField** *extends* `string` \| `number` + +#### Parameters + +##### fields + +`TField[]` + +An array of field keys to validate. + +##### cause + +`ValidationCause` + +The cause of the validation. + +#### Returns + +`Promise`\<[`ValidationError`](../type-aliases/validationerror.md)[]\> diff --git a/packages/form-core/src/FormApi.ts b/packages/form-core/src/FormApi.ts index 7f4ad8bc0..b6db54b06 100644 --- a/packages/form-core/src/FormApi.ts +++ b/packages/form-core/src/FormApi.ts @@ -811,6 +811,41 @@ export class FormApi< return fieldInstance.validate(cause) } + /** + * Validates an array of field in the form using the correct handlers for a given validation type. + */ + validateFields = async ( + fields: DeepKeys[], + cause: ValidationCause, + ) => { + // Validate the fields + const fieldValidationPromises: Promise[] = [] + batch(() => { + fields.forEach((field) => { + const fieldInstance = this.fieldInfo[field]?.instance + if (!fieldInstance) return + + // If any fields are not touched + if (!fieldInstance.state.meta.isTouched) { + // Mark them as touched + fieldInstance.setMeta((prev) => ({ + ...prev, + isTouched: true, + })) + } + + fieldValidationPromises.push( + Promise.resolve().then(() => + this.validateField(field, cause), + ), + ) + }) + }) + + const errorsArray = await Promise.all(fieldValidationPromises) + return errorsArray.flat() + } + /** * TODO: This code is copied from FieldApi, we should refactor to share * @private