I
I
Ivan Gvrl2020-06-19 20:25:30
WordPress
Ivan Gvrl, 2020-06-19 20:25:30

How do I validate the entered number for multiple countries at checkout?

I'm trying to write a code that will allow a store that works for Russia and Belarus to check the phone number for the operator code and the number of digits of the number, depending on the selected country of delivery. Not working yet. Can someone tell me what's wrong...

add_action('woocommerce_checkout_process', 'number_mask');
function number_mask() {
global $woocommerce;
if ( isset ($woocommerce->customer->get_country() <> 'BY' )) {
    isset($_POST['billing_phone']) && ! preg_match("/^(\+375)?[0-9 \-]{9,}/i", $_POST['billing_phone'])
        wc_add_notice(__('Пожалуйста введите <strong>Номер телефона</strong> с кодом оператора.'), 'error');
}
if ( isset ($woocommerce->customer->get_country() <> 'RU' )) {
    isset($_POST['billing_phone']) && ! preg_match("/^(\+7)?[0-9 \-]{10,}/i", $_POST['billing_phone'])
        wc_add_notice(__('Пожалуйста введите <strong>Номер телефона</strong> с кодом оператора.'), 'error');

}}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Gvrl, 2020-06-19
@Zoylander

As a result, I decided to use this solution:

add_action('woocommerce_checkout_process', 'custom_checkout_field_process');
function custom_checkout_field_process() {
    // Check the number phone
    if ( isset($_POST['billing_phone']) && ! preg_match("/^(7|\+7|8|375|\+375|8)?[0-9]{9,10}/", $_POST['billing_phone']) )
        wc_add_notice(__('Пожалуйста введите <strong>Номер телефона</strong> с кодом оператора.'), 'error');
}

I
Igor, 2020-06-19
@loonny

I'm not a WooCommerce expert, but what is that character <>in the code?
I can guess what it should have been.==

add_action('woocommerce_checkout_process', 'number_mask');
function number_mask() {
global $woocommerce;
if ( isset ($woocommerce->customer->get_country() == 'BY' )) {
    isset($_POST['billing_phone']) && ! preg_match("/^(\+375)?[0-9 \-]{9,}/i", $_POST['billing_phone'])
        wc_add_notice(__('Пожалуйста введите <strong>Номер телефона</strong> с кодом оператора.'), 'error');
}
if ( isset ($woocommerce->customer->get_country() == 'RU' )) {
    isset($_POST['billing_phone']) && ! preg_match("/^(\+7)?[0-9 \-]{10,}/i", $_POST['billing_phone'])
        wc_add_notice(__('Пожалуйста введите <strong>Номер телефона</strong> с кодом оператора.'), 'error');

}}

By the way, some enter numbers without a plus, and some through the eight in general, and these are all correct numbers. Therefore, I think this regular expression is better for Russian numbers. There is no point in setting the i flag, since all the numbers are in the same register and so on. And spaces and - can be removed from the string before checking PHP: Comparison Operators
/^(7|\+7|8)?[0-9]{10}/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question