Skip to content

Instantly share code, notes, and snippets.

@Preciousomonze
Last active April 26, 2019 20:24
Show Gist options
  • Save Preciousomonze/40c25703631d6ba65dc151efe633f3ca to your computer and use it in GitHub Desktop.
Save Preciousomonze/40c25703631d6ba65dc151efe633f3ca to your computer and use it in GitHub Desktop.
Custom phone validation on Woocommerce Checkout
<?php
/**
* For handling the extra fields displayed on checkout
*/
Class custom_checkout{
/**
* Construcdur :)
*/
public function __construct(){
//woocommerce things
add_action('woocommerce_after_checkout_validation', array($this,'checkout_validate'));
}
/**
* For extra custom validation
*
* @param array $data | the external data
* @hook woocommerce_after_checkout_validation
*/
public function checkout_validate($data){
$phone_valid_field = isset($_POST['ls_valid_phone']) ? trim(strtolower($_POST['ls_valid_phone'])) : false;
$phone_valid_err_field = isset($_POST['ls_phone_validate_err']) ? trim($_POST['ls_phone_validate_err']) : false;
if(!$phone_valid_field){//there was an error
wc_add_notice( __( $phone_valid_err_field, TEXT_DOMAIN ), 'error');
}
else{//to be continued :)
}
}
}
new custom_checkout();
var $ = jQuery;
//note there are some external scripts and values that serve as secondary characters, cant put them here, but these are enough to get the concept
var wcLsPhoneErrorMap = [ "Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];
//start
var wcLsPhoneIntl = $('.wc-ls-intl input').intlTelInput({
utilsScript: '{the intTelInput util script src here}'
});
//some globals
var wcLsphoneErrMsg = "";
/**
* Validates the phone number
*
* @param intlTelInput input
* @returns string or bool
*/
function wcLsValidatePhone(input){
const phone = input;
let result = false;
if(phone.intlTelInput("isValidNumber") == true){
result = phone.intlTelInput("getNumber");
}
else{
let errorCode = phone.intlTelInput("getValidationError");
wcLsphoneErrMsg = `Phone validation error: ${wcLsPhoneErrorMap[errorCode]}`;
}
return result;
}
//for woocommerce
var wcLsCheckoutForm = $('.woocommerce-checkout');
wcLsCheckoutForm.on('checkout_place_order',function(){
let phoneNumber = wcLsValidatePhone(wcLsPhoneIntl);
console.log(phoneNumber);
if(phoneNumber != false){//phone is valid
$('.woocommerce-checkout input#billing_phone').val(phoneNumber);//set the real value so it submits it along
if($('#wc-ls-phone-valid-field').length == 0){//append
wcLsCheckoutForm.append(`<input id="wc-ls-phone-valid-field" value="${phoneNumber}" type="hidden" name="${wcLsJson.phoneValidatorName}">`);
}
}
else{
if($('#wc-ls-phone-valid-field-err-msg').length == 0){//append
wcLsCheckoutForm.append(`<input id="wc-ls-phone-valid-field-err-msg" value="${wcLsphoneErrMsg}" type="hidden" name="${wcLsJson.phoneValidatorErrName}">`);
}
}
});
@allensmyllen
Copy link

yo man cooli love it kudos bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment