Hi @matatyahu
Just to make sure that I’ve understood your question correctly – you are looking forward to mark your custom fields as required and to display an error message when the data is entered in these fields incorrectly, have I gotten this right?
I believe you’ve tried adding this through custom code, and that you may not have coded the required fields correctly. You may want to go through this document: https://rudrastyh.com/woocommerce/checkout-fields.html which seems to address custom checkout fields in WooCommerce in detail.
I hope that gets you going.
Please feel free to let us know if you have any other questions. We are happy to help!
Many thanks @harishanker for getting back and the link!
Currently I inserted this code to add a custom validation of the billing phone field:
// Custom validation for Billing Phone checkout field
add_action(‘woocommerce_checkout_process’, ‘custom_validate_billing_phone’);
function custom_validate_billing_phone() {
$is_correct = preg_match(‘/^[0-9]{6,20}$/’, $_POST[‘billing_phone’]);
if ( $_POST[‘billing_phone’] && !$is_correct) {
wc_add_notice( __( ‘The Phone field should be between 6 and 20 digits.’ ), ‘error’ );
}
}
This works fine as I get an error message when the field is incorrect but, still, the field itself doesn’t get the class ‘woocommerce-invalid’ so it gets a red border too.
This was in fact a question of my client as he wants to make sure people notice which field has to be corrected.
I’ll go through the link you sent me and get back when I managed to solve the issue. : ))
Cheers,
Matthieu
Hello @harishanker,
I read your link and reworked the code a bit. So now the validation works.
When the billing first name field only contains one character the message ‘Billing First name is too short.’ appears. Nevertheless the field itself that contains the single character does not get the red border. How can I get this right? This is my code so far:
// Custom validation for Billing First Name checkout field
add_action(‘woocommerce_checkout_process’, ‘custom_validate_billing_first_name’);
function custom_validate_billing_first_name() {
$is_correct = preg_match(‘/^[a-zA-Z]{2,50}$/’, $_POST[‘billing_first_name’]);
if ( $_POST[‘billing_first_name’] && !$is_correct) {
wc_add_notice( __( ‘<!–:de–>Rechnung Vorname ist zu kurz.<!–:–><!–:en–>Billing First name is too short.<!–:–>’ ), ‘error’ );
}
}
Thanks in advance!
Best,
Matthieu
Plugin Support
John Coy a11n
(@johndcoy)
Automattic Happiness Engineer
Hi @matatyahu
This is more than we can help with here. For customizations we recommend one of the services listed on this page:
https://woocommerce.com/customizations/
Another option is to team up with a developer on our WooCommerce Developers Slack Channel:
https://woocommerceslack.herokuapp.com/