AD



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:


jQuery(document).ready(function ($) { // Listen for form submission $('form.checkout').on('submit', function (e) { const phoneField = $('#billing_phone'); // Change this if your field ID is different const phoneValue = phoneField.val(); const phoneRegex = /^[0-9]{10,15}$/; // Allow only numbers (10 to 15 digits) // Validate the phone number if (!phoneRegex.test(phoneValue)) { e.preventDefault(); // Prevent form submission alert('Please enter a valid phone number (10 to 15 digits).'); phoneField.focus(); phoneField.css('border', '2px solid red'); } else { phoneField.css('border', '1px solid #ccc'); // Reset border if valid } }); });

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:

php
add_action('woocommerce_checkout_process', 'validate_checkout_phone_number'); function validate_checkout_phone_number() { $phone = $_POST['billing_phone']; // Check if the phone number is valid if (!preg_match('/^[0-9]{10,15}$/', $phone)) { wc_add_notice(__('Please enter a valid phone number (10 to 15 digits).', 'woocommerce'), 'error'); } }

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

Previous Post Next Post