Ad

Handle Multiple Substrings In Woocommerce Validation Checkout Form

a few years ago someone added code to our website (Wordpress/Woocommerce Checkout), which validates a field against a prefix and field length.

The field validation code looks like this:

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    if ((substr($_POST['billing_manr'],0,3) <> "MA-") || (strlen($_POST['billing_manr']) <> 9))
    wc_add_notice( __( 'Error code ...' ), 'error' );
}

It validates against MA- and an allover length of 9 letters. For example, MA-123123 is OK, MA-123 isn't.

Now we want to validate against MA-xxxxxx and BW-xxxxxx but I'm not sure how the correct syntax is.

I tried already the following:

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    if ((substr($_POST['billing_manr'],0,3) <> "MA-") || (substr($_POST['billing_manr'],0,3) <> "BW-") || (strlen($_POST['billing_manr']) <> 9))
    wc_add_notice( __( 'Error code ...' ), 'error' );
}

But with this the validation fails again both, MA- and BW-.

Can someone help me with this?

Ad

Answer

The following using in_array() will handle both substrings as follow:

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
    if ( isset($_POST['billing_manr']) 
    && ( ! in_array( substr($_POST['billing_manr'], 0, 3), array('MA-', 'BW-') ) 
    || strlen($_POST['billing_manr']) <> 9 ) ) {
        wc_add_notice( __( 'Error code ...', 'woocommerce' ), 'error' );
    }
}

or using preg_match() too this way:

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
    if ( isset($_POST['billing_manr']) 
    && ( ! preg_match('/^MA-|BC-/', $_POST['billing_manr']) 
    || strlen($_POST['billing_manr']) <> 9 ) ) {
        wc_add_notice( __( 'Error code ...', 'woocommerce' ), 'error' );
    }
}

Tested and works.

Ad
source: stackoverflow.com
Ad