0

I was given a great help with my code of adding a field, now I would like ship to/account number to be numeric digits only.

Here is my current code:

// login Field validation
add_filter( 'woocommerce_login_errors', 'account_login_field_validation', 10, 3 );
function account_login_field_validation( $errors, $username, $email ) {
    if ( isset( $_POST['billing_account_number'] ) && empty( $_POST['billing_account_number'] ) ) {
        $errors->add( 'billing_account_number_error', __( '<strong>Error</strong>: account number is required!', 'woocommerce' ) );
    }
    return $errors;
}

// Display field in admin user billing fields section
add_filter( 'woocommerce_customer_meta_fields', 'admin_user_custom_billing_field', 10, 1 );
function admin_user_custom_billing_field( $args ) {
    $args['billing']['fields']['billing_account_number'] = array(
        'label'         => __( 'Ship to/ Account number', 'woocommerce' ),
        'description'   => '',
        'custom_attributes'   => array('maxlength' => 6),
    );
    return $args;
}

Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Hurab Nair
  • 55
  • 2
  • 6

1 Answers1

0

You can use the conditional ctype_digit() function to restrict the value to be numeric digits:

// login Field validation
add_filter( 'woocommerce_login_errors', 'account_login_field_validation', 10, 3 );
function account_login_field_validation( $errors, $username, $email ) {
    if ( isset( $_POST['billing_account_number'] ) && empty( $_POST['billing_account_number'] ) ) {
        $errors->add( 'billing_account_number_error', __( '<strong>Error</strong>: Account number is a required field.', 'woocommerce' ) );
    } elseif ( isset( $_POST['billing_account_number'] ) && ! ctype_digit($_POST['billing_account_number']) ) {
        $errors->add( 'billing_account_number_error', __( '<strong>Error</strong>: Only numeric digits are allowed on Account number field.', 'woocommerce' ) );
    }
    return $errors;
}

You could also use is_numeric() function…

Related: how to check if PHP variable contains non-numbers?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Hi Loic thank you very much you have been a great help for me everytime, this is he function you edited for me before as well – Hurab Nair Oct 04 '19 at 08:14