2023-03-14 12:37:28 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { __, sprintf } from '@wordpress/i18n';
|
|
|
|
|
2024-07-15 10:43:02 +00:00
|
|
|
const defaultValidityMessage =
|
|
|
|
( label: string | undefined ) =>
|
|
|
|
( validity: ValidityState ): string | undefined => {
|
|
|
|
const fieldLabel = label
|
|
|
|
? label.toLowerCase()
|
|
|
|
: __( 'field', 'woocommerce' );
|
|
|
|
|
|
|
|
const invalidFieldMessage = sprintf(
|
|
|
|
/* translators: %s field label */
|
|
|
|
__( 'Please enter a valid %s', 'woocommerce' ),
|
|
|
|
fieldLabel
|
|
|
|
);
|
|
|
|
|
|
|
|
if (
|
|
|
|
validity.valueMissing ||
|
|
|
|
validity.badInput ||
|
|
|
|
validity.typeMismatch
|
|
|
|
) {
|
|
|
|
return invalidFieldMessage;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2023-03-14 12:37:28 +00:00
|
|
|
/**
|
|
|
|
* Converts an input's validityState to a string to display on the frontend.
|
|
|
|
*
|
|
|
|
* This returns custom messages for invalid/required fields. Other error types use defaults from the browser (these
|
|
|
|
* could be implemented in the future but are not currently used by the block checkout).
|
|
|
|
*/
|
|
|
|
const getValidityMessageForInput = (
|
2024-07-15 10:43:02 +00:00
|
|
|
label: string | undefined,
|
|
|
|
inputElement: HTMLInputElement,
|
2024-07-15 15:22:42 +00:00
|
|
|
customValidityMessage?: ( validity: ValidityState ) => string | undefined
|
2023-03-14 12:37:28 +00:00
|
|
|
): string => {
|
|
|
|
// No errors, or custom error - return early.
|
2024-07-15 10:43:02 +00:00
|
|
|
if ( inputElement.validity.valid || inputElement.validity.customError ) {
|
2023-03-14 12:37:28 +00:00
|
|
|
return inputElement.validationMessage;
|
|
|
|
}
|
|
|
|
|
2024-07-15 10:43:02 +00:00
|
|
|
const validityMessageCallback =
|
|
|
|
customValidityMessage || defaultValidityMessage( label );
|
2023-03-14 12:37:28 +00:00
|
|
|
|
2024-07-15 10:43:02 +00:00
|
|
|
return (
|
|
|
|
validityMessageCallback( inputElement.validity ) ||
|
|
|
|
inputElement.validationMessage
|
|
|
|
);
|
2023-03-14 12:37:28 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export default getValidityMessageForInput;
|