WooCommerce Datepicker field on checkout page with 18 plus validation

You are here:
← All Topics

This article belongs to our plugin : WooCommerce Easy Checkout Field Editor

Use below given php code snippet to create datepicker field with 18 plus validation.

Do not forget to replace billing_field_504 with your field key. You need to create one field with datepicker as field type.

you may use Code Snippets plugin to inject any extra php code.

add_action( 'woocommerce_after_checkout_validation', 'pcfme_validate_adult_dob', 10, 2);

function pcfme_validate_adult_dob( $fields, $errors ){

    $enterd_dob = $fields[ 'billing_field_504' ];
    $pcfme_extra_settings = get_option('pcfme_extra_settings');
    $dt_format            = "Y-m-d";
    $current_date         = date($dt_format, time());
    $enterd_dob           = str_replace('/', '-', $enterd_dob);

    $your_date = date("Y-m-d", strtotime($enterd_dob) );

    $diff = abs(strtotime($current_date) - strtotime($your_date));

    $years = floor($diff / (365*60*60*24));

    if (!isset($years) ) {
        $errors->add( 'validation', 'Please enter your date of birth' );
    } 

    if (isset($years) && (($years < 18) || ($years == 0)) ) {
        $errors->add( 'validation', 'You must be 18 or older to buy this product.' );
    }

}

 

Sidebar