I am trying to validate the user input before adding it to the cart data, but the validation is always failing and I don't know why.
add_filter( 'woocommerce_add_to_cart_validation',
'func_validate_input', 10, 3 );
function func_validate_input( $passed, $product_id, $quantity ) {
$dimensions_array = range(10,50);
$val_height = (float) esc_attr($_POST['height']);
$val_length = (float) esc_attr($_POST['length']);
$val_width = (float) esc_attr($_POST['width']);
if( ! in_array($val_height, $val_length, $val_width, $dimensions_array))
{
$passed = false;
wc_add_notice( __( 'Please input the desired dimensions (10-50
centimeters))', 'cfwc' ), 'error' );
}
return $passed;
}
Ok, I think this is one way of doing it.
add_filter( 'woocommerce_add_to_cart_validation', 'func_validate_dimensions', 20, 3
);
function func_validate_dimensions( $passed, $product_id, $quantity ) {
if((! isset($_POST['height'])
|| (empty($_POST['height'])))
|| (! isset($_POST['length'])
|| (empty($_POST['length'])) )
|| (! isset($_POST['width'])
|| ( empty($_POST['width'])) ) ){
$passed = false;
wc_add_notice( __( 'Please enter desired dimensions (10-50
centimeters)', 'cfwc' ), 'error' );
}
$val_range = range(10,50);
$val_height = esc_attr($_POST['height']);
$val_length = esc_attr($_POST['length']);
$val_width = esc_attr($_POST['width']);
if (( ! in_array($val_height,$val_range)) ||
( ! in_array($val_length,$val_range)) ||
( ! in_array($val_width,$val_range))){
$passed = false;
wc_add_notice( __( 'Please enter desired dimensions (10-50
centimeters)', 'cfwc' ), 'error' );
}
return $passed;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.