skip to Main Content

I wrote a regular expression that validates the phone number in WooCommerce. It works in all cases, unless the field contains a single "0" character.

What could be the error?

That’s the code:

$post_value = $_POST['billing_phone'];   
if ( $post_value && ! preg_match( '/^(+49)[0-9]{9,}$/', $post_value ) ) {      
    //error                                         
}

2

Answers


  1. Your regex does not match 0 or +490. So the problem is probably that something in that if statement is different when the POST param 'billing_phone' is 0. In PHP if (int) is true for any int other than 0 and false for 0, perhaps that is the problem?

    So you could solve that by something like this:

    if ( ($post_value || $post_value == 0) && ! preg_match( '/^(+49)[0-9]{9,}$/', $post_value ) ) {
    

    (Disclaimer: I am generally not very familiar with PHP.)

    Login or Signup to reply.
  2. You could write the pattern using an alternation matching only a single zero.

    If you don’t need the separate capture group for the +49 for after processing you can omit it.

    ^(?:+49d{9,}|0)$
    

    See a regex demo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search