Checkout Utilities
Utility functions and React hooks for checkout functionality, available from @woocommerce/blocks-checkout.
useValidateCheckout
A hook that validates the checkout form and automatically scrolls to the first validation error if any are found.
This hook is primarily used internally by the PlaceOrderButton component to provide the validate prop to custom place order button components. However, it can also be used directly if needed.
Usage
// Aliased import
import { useValidateCheckout } from '@woocommerce/blocks-checkout';
// Global import
// const { useValidateCheckout } = wc.blocksCheckout;
const MyComponent = () => {
const validateCheckout = useValidateCheckout();
const handleClick = async () => {
const { hasError } = await validateCheckout();
if ( hasError ) {
// Validation failed - errors are automatically shown and
// the page scrolls to the first error
return;
}
// Validation passed - proceed with your logic
};
return <button onClick={ handleClick }>Validate</button>;
};
Return Value
The hook returns a function that, when called:
- Emits the
CHECKOUT_VALIDATIONevent to run all registered validation callbacks - Checks the validation store for any field-level validation errors
- If errors are found:
- Shows all validation errors
- Scrolls to and focuses the first error element
- Returns a promise that resolves to
{ hasError: boolean }
| Property | Type | Description |
|---|---|---|
hasError | boolean | true if validation failed, false if passed. |