Reputation: 483
I have added in checkout page a acceptance field below the terms and conditions field. The new field is about the age validation.
In frontend, I can see my checkbox but customer should not be able to order if checking this checkbox in not checked. This is the generated html code:
<?php if ( wc_terms_and_conditions_checkbox_enabled() ) : ?>
<p class="form-row validate-required">
<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="terms" <?php checked( apply_filters( 'woocommerce_terms_is_checked_default', isset( $_POST['terms'] ) ), true ); // WPCS: input var ok, csrf ok. ?> id="terms" />
<span class="woocommerce-terms-and-conditions-checkbox-text"><?php wc_terms_and_conditions_checkbox_text(); ?></span> <span class="required">*</span>
</label>
<input type="hidden" name="terms-field" value="1" />
</p>
<?php endif; ?>
<p class="form-row validate-required">
<label class="woocommerce-form__label woocommerce-form__label-for-checkbox checkbox">
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" required name="validationage" id="validationage" />
<span class="woocommerce-terms-and-conditions-checkbox-text"><?php _e( 'Je certifie avoir + de 18 ans', 'woocommerce'); ?></span> <span class="required">*</span>
</label>
</p>
How to enable the validation for this checkbox?
Upvotes: 1
Views: 1850
Reputation: 794
It would be much better if you use woocommerce_after_checkout_validation hooks, this will let you to be sync with other WooCommerce validation error
add_action( 'woocommerce_after_checkout_validation', function( $data, &$errors ) {
$field_id = 'validationage';
if( ! isset( $data[$field_id] ) || empty( $data[$field_id] ) ) {
$errors->add( 'terms', __( 'validation text.', 'theme-slug' ) );
}
},10, 2 );
Note: You may need to use woocommerce_checkout_fields filter hook to add custom checkout field.
Thanks
Upvotes: -1
Reputation: 253763
The following will handle your custom checkbox field validation on checkout page:
add_action('woocommerce_checkout_process', 'custom_checkbox_checkout_validation');
function custom_checkbox_checkout_validation() {
$field_id = 'validationage';
if( ! isset( $_POST[$field_id] ) || empty( $_POST[$field_id] ) )
wc_add_notice( __("validation text.","woocommerce"), "error" );
}
Code goes in functions.php file of your active child theme (or active theme). It should works.
Upvotes: 4