Provide recently updated data for the validate function in the useValidation hook (#43320)

* Allow providing recently updated data for the validate function in the useValidation hook

* set newData parameter as optional
This commit is contained in:
Nathan Silveira 2024-01-08 12:12:10 -03:00 committed by GitHub
parent ebb6b0fe54
commit 245fea22ac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 17 additions and 8 deletions

View File

@ -0,0 +1,4 @@
Significance: minor
Type: add
Allow providing recently updated data for the validate function in the useValidation hook

View File

@ -167,7 +167,7 @@ export function Edit( {
dateOnSaleFromGmtValidationError && 'has-error'
}
help={ dateOnSaleFromGmtValidationError as string }
onBlur={ validateDateOnSaleFromGmt }
onBlur={ () => validateDateOnSaleFromGmt() }
/>
</div>
@ -190,7 +190,7 @@ export function Edit( {
.toISOString()
)
}
onBlur={ validateDateOnSaleToGmt }
onBlur={ () => validateDateOnSaleToGmt() }
className={
dateOnSaleToGmtValidationError && 'has-error'
}

View File

@ -2,7 +2,7 @@ export type ValidatorResponse = Promise< ValidationError >;
export type Validator< T > = (
initialValue?: T,
newData?: Partial< T >
newData?: Record< string, unknown >
) => ValidatorResponse;
export type ValidationContextProps< T > = {
@ -12,7 +12,10 @@ export type ValidationContextProps< T > = {
validator: Validator< T >
): React.Ref< HTMLElement >;
unRegisterValidator( validatorId: string ): void;
validateField( name: string ): ValidatorResponse;
validateField(
name: string,
newData?: Record< string, unknown >
): ValidatorResponse;
validateAll( newData?: Partial< T > ): Promise< ValidationErrors >;
};

View File

@ -33,11 +33,13 @@ export function useValidation< T >(
ref,
error: context.errors[ validatorId ],
isValidating,
async validate() {
async validate( newData?: Record< string, unknown > ) {
setIsValidating( true );
return context.validateField( validatorId ).finally( () => {
setIsValidating( false );
} );
return context
.validateField( validatorId, newData )
.finally( () => {
setIsValidating( false );
} );
},
};
}