I have a plugin which has this method in it that is supposed to have a hook for custom validation. I have two issues:
- I’m not sure how to call it (have posted my attempt below)
- It looks like the plugin has a bug in it because I can’t get at $cart_key?
Plugin code with the hook:
public function validateCustomFields( $value, $form_id, $cart_key )
{
$decoded_value = json_decode( $value );
$fields = array();
foreach ( json_decode( get_option( 'bookly_custom_fields' ) ) as $field ) {
$fields[ $field->id ] = $field;
}
foreach ( $decoded_value as $field ) {
if ( isset( $fields[ $field->id ] ) ) {
if ( ( $fields[ $field->id ]->type == 'captcha' ) && ! Captcha\Captcha::validate( $form_id, $field->value ) ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Incorrect code', 'bookly' );
} elseif ( $fields[ $field->id ]->required && empty ( $field->value ) && $field->value != '0' ) {
$this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' );
} else {
/**
* Custom field validation for a third party,
* if the value is not valid then please add an error message like in the above example.
*
* @param \stdClass
* @param ref array
* @param \stdClass
*/
do_action_ref_array( 'bookly_validate_custom_field', array( $field, &$this->errors, $fields[ $field->id ] ) );
}
}
}
}
My code in functions.php:
/**
* Adds the custom validator for postcodes
*/
function postcode_custom_validator_action($field, $errors, $fieldId) {
if ( $fieldId == 16020 ) {
$postcodesCoveredSetting = get_theme_mod( 'postcode_textbox' );
if(!isValidPostcode($field->value, $postcodesCoveredSetting)) {
// Validator.php says: "if the value is not valid then please add an error message like in the above example."
// which looks like this:
// $this->errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Required', 'bookly' );
// but $cart_key not passed through it seems?
$errors['custom_fields'][ $cart_key ][ $field->id ] = __( "Sorry, we only cover " . $postcodesCoveredSetting . " postcode areas at the moment", 'bookly' );
}
}
}
add_action ( 'bookly_validate_custom_field', 'postcode_custom_validator_action', 10, 3 ); // 10 is priority, 3 is number of params in array?
1 Answer
I haven’t tested this yet but somebody suggested this:
add_action( 'bookly_validate_custom_field', function ( \stdClass $field, &$errors, $cart_key, \stdClass $field_info ) {
// Validation by custom_field id
switch ( $field->id ) {
case 'id_value':
if ( /*$invalid == */ true ) {
$errors['custom_fields'][ $cart_key ][ $field->id ] = __( 'Invalid', 'bookly' );
}
break;
}
}, 10, 4 );