• Resolved renato12

    (@renato12)


    I’m trying to validate the next code of woocommerce to only accept 10 digits not more and not less. I already found a regex but not sure why I still can put more than 10 digits yet

    /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/

    the code on the woocommerce files is:

    /**
    * Validates a phone number using a regular expression
    *
    * @param string phone number
    * @return bool
    */
    public static function is_phone( $phone ) {
    if ( strlen( trim( preg_replace( ‘/[\s\#0-9_\-\+\(\)]/’, ”, $phone ) ) ) > 0 )
    return false;

    return true;
    }

    https://www.ads-software.com/plugins/woocommerce/

Viewing 5 replies - 1 through 5 (of 5 total)
  • Plugin Contributor Claudio Sanches

    (@claudiosanches)

    You can validade with your regex.

    Here an example:

    function my_wc_validate_phone_number() {
    	$phone = isset( $_POST['billing_phone'] ) : trim( $_POST['billing_phone'] ) : '';
    	if ( ! preg_match( '/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/', $phone ) ) {
    		wc_add_notice( __( 'Invalid Phone Number. Please enter with a valid fone number. Eg: (123) 456 7890' ), 'error' );
    	}
    }
    
    add_action( 'woocommerce_checkout_process', 'wc_validate_phone_number' );
    
    Thread Starter renato12

    (@renato12)

    @claudio Sanches
    i tried your code but seems like doesnt work.

    Parse error: syntax error, unexpected ‘:’ in functions.php on line 1131

    changed the “:” for “;” and it doesnt show the error msg but doesnt work.

    There were a lot of mistakes in that code. I made some changes, this works for me:

    /* Add phone validation */
    function wc_validate_phone_number() {
    	$phone = (isset( $_POST['billing_phone'] ) ? trim( $_POST['billing_phone'] ) : '');
    	if ( ! preg_match( '/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/', $phone ) ) {
    		wc_add_notice( __( 'Invalid Phone Number. Please enter with a valid phone number. Eg: (123) 456 7890' ), 'error' );
    	}
    }
    
    add_action( 'woocommerce_checkout_process', 'wc_validate_phone_number' );
    /* End */

    Hi,

    How can I add placeholder for phone field on this code?

    Thank you!

    Plugin Contributor Mike Jolley

    (@mikejolley)

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘phone validation woocommerce’ is closed to new replies.