Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Only validate postcode if its required or filled #9377

Merged
merged 3 commits into from
May 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
defaultAddressFields,
ShippingAddress,
} from '@woocommerce/settings';
import { useSelect, useDispatch } from '@wordpress/data';
import { useSelect, useDispatch, dispatch } from '@wordpress/data';
import { VALIDATION_STORE_KEY } from '@woocommerce/block-data';
import { FieldValidationStatus } from '@woocommerce/types';

Expand Down Expand Up @@ -123,6 +123,23 @@ const AddressForm = ( {
} );
}, [ addressFormFields, onChange, values ] );

// Clear postcode validation error if postcode is not required.
useEffect( () => {
addressFormFields.forEach( ( field ) => {
if ( field.key === 'postcode' && field.required === false ) {
const store = dispatch( 'wc/store/validation' );

if ( type === 'shipping' ) {
store.clearValidationError( 'shipping_postcode' );
}

if ( type === 'billing' ) {
store.clearValidationError( 'billing_postcode' );
}
}
} );
}, [ addressFormFields, type, clearValidationError ] );

useEffect( () => {
if ( type === 'shipping' ) {
validateShippingCountry(
Expand Down Expand Up @@ -265,11 +282,13 @@ const AddressForm = ( {
} )
}
customValidation={ ( inputObject: HTMLInputElement ) =>
customValidationHandler(
inputObject,
field.key,
values
)
field.required || inputObject.value
? customValidationHandler(
inputObject,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think these checks should be inside the customValidationHandler if possible. The customValidationHandler should receive another parameter isOptional, defaulted to false and should handle the logic inside.

field.key,
values
)
: true
}
errorMessage={ field.errorMessage }
required={ field.required }
Expand Down