In a WordPress checkout page (such as Woo Commerce), you can validate the contact number field using JavaScript/jQuery for client-side validation and use PHP hooks for server-side validation.
1. Client-Side Validation using jQuery
Add the following script to your WordPress theme's functions.php
or a custom JS file:
Explanation:
- This script targets the
#billing_phone
field (WooCommerce uses this ID for the phone number input by default). - It checks if the phone number contains only digits and has a length between 10 and 15.
- If the validation fails, it prevents the form from submitting and shows an alert message.
2. Server-Side Validation using WooCommerce Hook
In your theme’s functions.php
file, add this PHP code for server-side validation:
Explanation:
- The
woocommerce_checkout_process
action hook validates the phone number when the form is submitted. - If the phone number does not match the specified format, it shows an error message on the checkout page.
3. Customizing the Phone Number Format (Optional)
You can adjust the regular expression (/^[0-9]{10,15}$/
) to allow different formats, such as:
- With country code:
/^\+?[0-9]{10,15}$/
(allows an optional+
at the start). - Allowing dashes/spaces:
/^[0-9\s-]{10,15}$/
.
4. Ensuring Compatibility with Caching Plugins
If you are using caching plugins like WP Rocket or W3 Total Cache, make sure to exclude the checkout page from caching to ensure proper validation.
Let me know if you need further customization or have specific requirements for the phone number format!
Post a Comment