/**
 * Validate [tel] field value if is a valid Israeli phone number.
 *
 * @param WPCF7_Validation $result field validation object.
 * @param WPCF7_Shortcode  $tag    field tag object.
 *
 * @return WPCF7_Validation
 */
function dorzki_validate_phone_number( $result, $tag ) {

	if( 'phone' !== strtolower( $tag->name ) ) {
		return $result;
	}

	$phone_number = $_POST[ $tag->name ];
	$phone_regex = '/^0?(([23489]{1}\d{7})|[5]{1}\d{8})$/';

	if( $tag->is_required() && empty( $phone_number ) ) {

		$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );

	} else {

		if( ! preg_match( $phone_regex, $phone_number ) ) {

			$result->invalidate( $tag, __( 'Please enter valid phone number.', 'dorzki' ) );

		}

	}

	return $result;

}

add_filter( 'wpcf7_validate_tel*', 'dorzki_validate_phone_number', 20, 2 );

Credit: dorzki.co.il

How to use it?

Usually adding functionality to a WordPress site is by creating a plugin.
However you can simply copy the code and paste it in your child theme’s functions.php file at the end of the file, just before ?>.

For JavaScript code you will need to add them to your theme’s main JavaScript file.

Having issues with the code?

If the code doesn’t work or you get an error please let us know in the comments section.
We will do our best to fix it as-soon-as-possible and update the code on this page.

Comments

Leave a Reply