jrobinsonc
10/7/2016 - 4:30 PM

Regular expresions (regex) validations

Regular expresions (regex) validations

function validateForm($form) {
    var isValid = true;
    var invalidFields = [];
    var validationRules = {
        email: /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        tel: /^(?:(\+1)(?:\D)?)?\(?(\d{3})\)?\D?(\d{3})\D?(\d{4})$/
    }

    $form.find(':input').each(function(){
        var $field = $(this);
        var label = $field.attr('placeholder');
        var value = $field.val().trim();
        
        switch (true) {
            // Field is empty:
            case $field.is(':required') && value === '':
            // Value is valid:
            case $field.attr('type') in validationRules && !validationRules[$field.attr('type')].test(value):
                isValid = false;
                invalidFields.push(label);
            break;
        }

    });

    if (invalidFields.length > 0) {
        alert("Following fields are required:\n\n- " + invalidFields.join("\n- "));
    }

    return isValid;
}

jQuery(document).ready(function($) {
    var $contactForm = $('.contact-form');

    $contactForm.on('submit', function(event) {

        if (!validateForm($contactForm)) {
            event.preventDefault();
            return false;
        }
    });
});

Regexp Expressions

For testing: Regex101

Rules

Phone numbers:

^(?:(\+1)(?:\D)?)?\(?(\d{3})\)?\D?(\d{3})\D?(\d{4})$

Date:

// mm/dd/yyyy
^(0[1-9]|1[012])/(0[1-9]|1[0-9]|2[0-9]|3[01])/([0-9]{4})$

Zip Codes:

^([0-9]{5})(\-[0-9]{4})?$