I'm trying to validate a custom checkout field against a regex expression so that it is a very specifically formatted date.
Here's my code:
add_action('woocommerce_after_checkout_validation', array($this, 'bkf_dd_checkout_validation'), 10, 2 );
add_action('wp_footer', array($this, 'bkf_dd_checkout_validation_js'));
function bkf_dd_checkout_validation( $fields, $errors ){
if( ! preg_match( '/[a-zA-Z]{6,9}\,\ \d{1,2}\ [a-zA-Z]{3,9}\ \d{4}/', $fields['delivery_date'] ) ){
$errors->add( 'validation', 'Please select a <strong>Delivery Date</strong> via the datepicker.' );
}
}
function bkf_dd_checkout_validation_js(){
if( ! is_checkout() ) {
return;
}
?>
<script>
jQuery(function($){
$( 'body' ).on( 'blur change', '#delivery_date', function(){
const wrapper = $(this).closest( '.form-row' );
if( ! /[a-zA-Z]{6,9}\,\ \d{1,2}\ [a-zA-Z]{3,9}\ \d{4}/.test( $(this).val() ) ) {
wrapper.addClass( 'woocommerce-invalid' );
wrapper.removeClass( 'woocommerce-validated' );
} else {
wrapper.addClass( 'woocommerce-validated' );
}
});
});
</script>
<?php
}
The JS is working, but the error is being set regardless of the value, ie. this displays even if field is valid (and set as green by the JS)
(the date format: Friday, 30 December 2022)
Any ideas?
CodePudding user response:
Solution as provided by Vijay Hardaha
Replace $fields['delivery_date']
with $_POST['delivery_date']