Search code examples
preg-matchcontactsphone-number

How to disallow repeated numbers in telephone field like 1111111 or 222222


I am using contact form 7 and want to disallow users to enter repeated numbers like 1111111 or 2222222 in phone field.

I am using below code to enter only 10 digits. Can anyone help me with what I should change or add in this to work.

// define the wpcf7_is_tel callback<br> 
function custom_filter_wpcf7_is_tel( $result, $tel ) {<br> 
  $result = preg_match( '/^\(?\+?([0-9]{0})?\)?[-\. ]?(\d{10})$/', $tel );<br>
  return $result; <br>
}<br>
         
add_filter( 'wpcf7_is_tel', 'custom_filter_wpcf7_is_tel', 10, 2 );

Solution

  • First of all, [0-9]{0} looks like a typo as this pattern matches nothing, an empty string. You probably wanted to match an optional area code, three digits. So, use \d{3} if you meant that.

    Next, to disallow same digits within those you match with \d{10}, you simply need to re-write it as (?!(\d)\1{9})\d{10}.

    Bearing in mind what was said above, the solution is

    function custom_filter_wpcf7_is_tel( $result, $tel ) {<br> 
      return preg_match('/^\(?\+?(?:\d{3})?\)?[-. ]?(?!(\d)\1{9})\d{10}$/', $tel );<br>
    }
    

    See the regex demo.