This code snippet is a Wordpress / Woocommerce PHP function called validate_mobile_number() that validates a mobile phone number submitted via a form. Please insert it into your theme's functions.php file.
Here's an explanation of how it works:
-
The function first retrieves the mobile phone number from the billing_phone field in the $_POST superglobal array.
-
It defines an array $valid_formats that contains regular expressions representing valid mobile phone number formats. In this case, the formats are +35385xxxxxxx, +35386xxxxxxx, and +35387xxxxxxx, and +35383xxxxxxx.
-
The function then iterates over each format in the $valid_formats array using a foreach loop.
-
For each format, it uses the preg_match() function to check if the billing_mobile_number matches the format. If a match is found, the function immediately returns true, indicating that the mobile number is valid.
-
If none of the formats match the billing_mobile_number, the function proceeds to the next format in the loop.
-
After the loop completes without finding a match, it executes the wc_add_notice() function. This function is typically used in the context of a WooCommerce store and displays an error notice to the user, indicating that the mobile number format is incorrect.
The error notice message states: "Please correct the format of your mobile number: +35385xxxxxxx or +35386xxxxxxx or +35387xxxxxxx or +35383xxxxxxx.")
// www.websitefunctions.com
add_action( 'woocommerce_checkout_process', 'validate_mobile_number' );
function validate_mobile_number() {
$billing_mobile_number = $_POST['billing_phone'];
$valid_formats = array('/^\+35385[0-9]{7}$/', '/^\+35386[0-9]{7}$/', '/^\+35383[0-9]{7}$/', '/^\+35387[0-9]{7}$/');
foreach ($valid_formats as $format) {
if (preg_match($format, $billing_mobile_number)) {
return true;
}
}
wc_add_notice( __( 'Please correct the format of your mobile number: +35385xxxxxxx or +35386xxxxxxx or +35387xxxxxxx or +35383xxxxxxx.' ), 'error' );
}
This snippet can be used in a form validation process within a WordPress or WooCommerce environment to ensure that the mobile number is in the specified valid formats.
Please modify the format according to the conventions used in your country.