bux23
7/10/2018 - 8:22 PM

Woocommerce checkout validation

Woocommerce checkout validation with, mapbox autocmplete for address. must include mapbox sdk from cdn and jqueryvalidate

var mapboxEngine = new MapboxClient('MAPBOX_KEY');

function wopecko_validations() {

    var $this = this;

    this.init =  function() {
        this.rules();
        this.checkout_validator();
        this.find_address("#billing_address_1");
    },

    this.find_address = function(fields) {
        jQuery(fields).each(function(index, el) {
            var field       = jQuery(this);
            var id          = field.attr('id');
            var list        = 'datalist-' + id;
            var listEl      = '<datalist id="' + list + '" class="woplist"></datalist>';
            field.attr('list', list);
            $(listEl).insertAfter(field);
            field.on('keydown', function() {
                var val = jQuery(this).val();
                var datalist = $('#datalist-' + id);
                if(val.length > 5) {
                    datalist.html('');
                    mapboxEngine.geocodeForward(val, function(err, data, res) {
                         data.features.forEach(function(row) {
                            var address  = row.place_name;
                            datalist.append("<option value='" + address + "'>" + address + "</option>");
                        });
                    });
                }
            });
        });
    },

    this.rules = function() {
        //codice fiscale
        jQuery.validator.addMethod("fiscalcode", function (value) {
            var regex = /[A-Za-z]{6}[\d]{2}[A-Za-z][\d]{2}[A-Za-z][\d]{3}[A-Za-z]/;
            return value == "" || value.match(regex);
        });
        //consensi obbligatori
        jQuery.validator.addMethod("mandatory_radio", function (value) {
            return value == "1";
        });
        //num tel italy no prefix
        jQuery.validator.addMethod("phone_noprefix_it", function (value) {
            var regex = /^(0|3)[0-9]{8,12}$/;
            return value == "" || value.match(regex);
        });
        //num tel italy prefix
        jQuery.validator.addMethod("phone_prefix_it", function (value) {
            var regex = /^((\+|00)39)?(\d{9,10})$/;
            return value == "" || value.match(regex);
        }); 
        //num tel intenrational
        jQuery.validator.addMethod("phone_intl", function (value) {
            var regex = /^(((\+|00)\d{2,3})|((\+1|001)(\d{3}|)))?(\d{9,10})$/;
            return value == "" || value.match(regex);
        });  
        //num cap
        jQuery.validator.addMethod("cap", function (value) {
            var regex = /^[0-9]{5}$/;
            return value == "" || value.match(regex);
        });
        //num email 2
        jQuery.validator.addMethod("email", function (value) {
            var regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
            return value == "" || value.match(regex);
        });
        //num email 2
        jQuery.validator.addMethod("email_confirm", function (value) {
            var email1 = $('#billing_email').val();
            return value == "" || value == email1;
        });
        //num date d/m/y
        jQuery.validator.addMethod("date_d_m_y", function (value) {
            var regex = /^((3[01]|[12][0-9]|0[1-9])\/(0[1-9]|1[012])\/(19|20)\d{2})$/;
            return value == "" || value.match(regex);
        });  
        //literal
        jQuery.validator.addMethod("literal", function (value) {
            var regex = /[A-Za-z0-9àáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-]+/;
            return value == "" || value.match(regex);
        }); 
        //number
        jQuery.validator.addMethod("number", function (value) {
            var regex = /[0-9]+/;
            return value == "" || value.match(regex);
        }); 
        //company
        jQuery.validator.addMethod("company", function (value) {
            var regex = /[A-Za-zàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-]+/;
            return value == "" || value.match(regex);
        }); 
        //address
        jQuery.validator.addMethod("address", function (value) {
            var regex = /[0-9\p{L} ./-]+/;
            return value == "" || value.match(regex);
        }); 
        //medium password - 8 chars, 1 caps, 1 normal, 1 number
        jQuery.validator.addMethod("medium_pass", function (value) {
            var regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!$%@#£€*?&]{8,}$/;
            return value == "" || value.match(regex);
        });
        //strong password - 8 char, 1 caps, 1 small, 1 numer, 1 special char
        jQuery.validator.addMethod("strong_pass", function (value) {
            var regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/;
            return value == "" || value.match(regex);
        }); 
    
    },

    this.diff_shipping = function() {
        return jQuery('#ship-to-different-address-checkbox').is(':checked');
    },

    this.create_account = function() {
        return jQuery('#createaccount').is(':checked');
    },

    this.get_caps = function() {
        jQuery.getJSON(publicFolder + "/json/caps.min.json", function(data){
            return data.codes;
        });
    },

    this.validation_settings = {
        ignore: ":hidden, input[readonly='readonly']",
        focusCleanup: true,
        onfocusout: function (element) {
            jQuery(element).valid();
        },
        onkeyup: false,
        rules: {
            "billing_first_name": {
                required: true,
                literal: true
            },
            "billing_last_name": {
                required: true,
                literal: true
            },
            "billing_age": {
                required: true,
                literal: true
            },
            "billing_company": {
                company: true
            },
            "billing_address_1": {
                required: true,
                literal: true
            },
            "billing_postcode": {
                required: true,
                cap: true
            },
            "billing_city": {
                required: true,
                literal: true
            },
            "billing_state": {
                required: true,
                literal: true
            },
            "billing_phone": {
                required: true,
                phone_prefix_it: true
            },
            "billing_email": {
                required: true,
                email: true
            },
            "billing_email_confirm": {
                required: true,
                email_confirm: true
            },
            "account_password": {
                required: {
                    depends: $this.create_account()
                },
                medium_pass: {
                    depends: $this.create_account()
                }
            },
            // different shipping address woocommerce
            "shipping_first_name": {
                required: {
                    depends: $this.diff_shipping()
                },
                literal: {
                    depends: $this.diff_shipping()
                }
            },
            "shipping_last_name": {
                required: {
                    depends: $this.diff_shipping()
                },
                literal: {
                    depends: $this.diff_shipping()
                }
            },
            "shipping_company": {
                company: {
                    depends: $this.diff_shipping()
                }
            },
            "shipping_address_1": {
                required: {
                    depends: $this.diff_shipping()
                },
                address: {
                    depends: $this.diff_shipping()
                }
            },
            "shipping_city": {
                required: {
                    depends: $this.diff_shipping()
                },
                literal: {
                    depends: $this.diff_shipping()
                }
            },
            "shipping_state": {
                required: {
                    depends: $this.diff_shipping()
                },
                literal: {
                    depends: $this.diff_shipping()
                }
            },
            "shipping_postcode": {
                required: {
                    depends: $this.diff_shipping()
                },
                cap: {
                    depends: $this.diff_shipping()
                }
            }
        },
        messages: {
            "billing_first_name": {
                required: "Inserisci un nome",
                literal: "Caratteri non consentiti"
            },
            "billing_last_name": {
                required: "Inserisci un cognome",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "billing_age": {
                required: "Inserisci un'età'",
                literal: "Sono ammessi solo numeri"
            },
            "billing_company": {
                company: "Sono stati inseriti caratteri non consentiti"
            },
            "billing_address_1": {
                required: "Inserisci un indirizzo",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "billing_postcode": {
                required: "Inserisci un cap",
                cap: "cap non valido"
            },
            "billing_city": {
                required: "Inserisci una città",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "billing_state": {
                required: "Seleziona una provincia",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "billing_phone": {
                required: "Inserisci un numero di telefono",
                phone_prefix_it: "numero non valido"
            },
            "billing_email": {
                required: "Inserisci una email",
                email: "indirizzo email non valido"
            },
            "billing_email_confirm": {
                required: "Conferma l'indirizzo email",
                email_confirm: "Le email non combaciano"
            },
            "account_password": {
                required: "Inserisci una password",
                medium_pass: "La password deve esere almeno di 8 caratteri, deve contenere almeno un numero, una lettera maiuscola, ed una minuscola"
            },
            // different shipping address woocommerce
            "shipping_first_name": {
                required: "Inserisci un nome",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "shipping_last_name": {
                required: "Inserisci un cognome",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "shipping_company": {
                company: "Sono stati inseriti caratteri non consentiti"
            },
            "shipping_address_1": {
                required: "Inserisci un indirizzo",
                address: "Sono stati inseriti caratteri non consentiti"
            },
            "shipping_city": {
                required: "Inserisci una città",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "shipping_state": {
                required: "Seleziona una provincia",
                literal: "Sono stati inseriti caratteri non consentiti"
            },
            "shipping_postcode": {
                required: "Inserisci un cap",
                cap: "Cap non valido"
            }
        }
    },

    this.checkout_validator = function() {
        var form    = jQuery("form.woocommerce-checkout");
        var submit  = jQuery("#place_order");
        var notice  = function() {
            alertify.error('Sono presenti campi obbligatori non compilati');
        };

        $this.check_guests();

        form.validate($this.validation_settings);

        submit.on('click',function(e) {
            var isvalid = form.valid();
            if(!isvalid) {
                e.preventDefault();
                e.stopImmediatePropagation();
                notice();
            }
        });
        form.on('submit',function(e) {
            var isvalid = jQuery(this).valid();
            if(!isvalid) {
                e.preventDefault();
                e.stopImmediatePropagation();
                notice();
            }
        })
    },

    this.check_guests = function() {
        if($('.guest-info-row').length) {
            guest_rows = $('.guest-info-row');
            guest_rows.each(function(i, el) {
                i++;
                // name
                $this.validation_settings.rules["guest_first_name_" + i] = {
                    "required": true,
                    "literal": true
                }
                $this.validation_settings.messages["guest_first_name_" + i] = {
                    "required": "Inserisci un nome",
                    "literal": "Caratteri non consentiti"
                }
                // last name
                $this.validation_settings.rules["guest_last_name_" + i] = {
                    "required": true,
                    "literal": true
                }
                $this.validation_settings.messages["guest_last_name_" + i] = {
                    "required": "Inserisci un cognome",
                    "literal": "Caratteri non consentiti"
                }
                // age
                $this.validation_settings.rules["guest_age_" + i] = {
                    "required": true,
                    "number": true
                }
                $this.validation_settings.messages["guest_age_" + i] = {
                    "required": "Inserisci un'età",
                    "literal": "Sono ammessi solo numeri"
                }
            });
        }
    },

    this.date_formatter = function(fields) {
        jQuery(fields).on('keydown', function(event) {
            var field = jQuery(this);
            var value = field.val();
            var len   = value.length;
            var key   = event.keyCode || event.charCode || event.which;
            // limit length
            field.attr('maxlength','10');
            if(value.length > 10){
                event.preventDefault();
            }
            // block double slashes
            if((len != 2 || len != 5) && event.shiftKey){
                event.preventDefault();
            } 
            // enable deletion
            if (key == 8 || key == 46 || key == 16 || key == 191 || len ==  10)  {
                return;
            }
            // add slash
            if (len == 2 || len == 5) {
                if(value[value.length - 1] != "/") {
                    field.val(value + "/");
                }
            }
        });
    }

}

jQuery(document).ready(function($) {
    var woo_validator = new wopecko_validations();
    woo_validator.init();
});