JavaScript Form Validation

Ciprian on Monday, July 4, 2022 in JavaScript DOM, Methods, Events and Scopes

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

This JavaScript code snippet adds inline validation to any form field (input, select and textarea).

JavaScript

/**
 * Match an element against a given pattern and add a visual hint
 */
function cgPatternMatch(element, pattern) {
    if ((element.value).match(pattern)) {
        cgToggleError(element, 'valid');
    } else {
        cgToggleError(element, 'invalid');
    }
}

/**
 * Match an element against a given value
 *
 * return bool
 */
function cgValueMatch(e) {
    return (e.value !== '') ? true : false;
}

/**
 * Check if email and email confirmation elements match and add a visual hint
 */
function cgEmailValidate(e1, e2) {
    let pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (
        e1.value === e2.value &&
        pattern.test(e1.value) &&
        pattern.test(e2.value)
    ) {
        cgToggleError(e2, 'valid');
    } else {
        cgToggleError(e2, 'invalid');
    }
}

/**
 * Match an element against a given pattern (based on validation type) and add a visual hint
 */
 function cgFormValidate(element, type) {
    if (type === 'alpha') {
        let pattern = /^[a-zA-Z\-'.\s]+$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'numeric') {
        let pattern = /^[0-9]{1,10}$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'alphanumeric') {
        let pattern = /^[,'a-zA-Z0-9\-\s]+$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'date') {
        let pattern = /^[,'0-9\/\s]+$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'email') {
        let pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

        cgPatternMatch(element, pattern);
    } else if (type === 'dropdown') {
        if (element.value === '') {
            cgToggleError(element, 'invalid');
        } else {
            cgToggleError(element, 'valid');
        }
    }
}

/**
 * Display error message based on current element's data attributes
 */
function cgToggleError(element, status) {
    let errorMessage = element.dataset.validationErrorMsg,
        errorContainer = element.dataset.validationErrorMsgContainer;

    element.className = status;

    if (status === 'valid') {
        errorContainer.innerHTML = errorMessage;
        errorContainer.style.display = 'none';
    } else if (status === 'invalid') {
        errorContainer.innerHTML = errorMessage;
        errorContainer.style.display = 'block';
    }
}

window.onload = () => {
    let inputElement = document.querySelector('.elementClass');

    inputElement.addEventListener('blur', () => {
        let inputValue = this.value;
        let inputValidationType = this.dataset.validationType;

        cgFormValidate(this, inputValidationType);
    });

    // Validate email address and email address confirmation
    let emailElement1 = document.querySelector('.elementClass1'),
        emailElement2 = document.querySelector('.elementClass2');
    emailElement.addEventListener('blur', () => {
        cgEmailValidate(emailElement1, emailElement2);
    });
}

HTML

<input type="text" name="fieldName" id="fieldName" data-validation-type="alphanumeric" data-validation-error-msg="Please fill in this field" data-validation-error-msg-container="#fieldName-error-dialog">
<div id="fieldName-error-dialog" class="field-error"></div>

Now, you need to change data-validation-type="" to:

data-validation-type="alpha"
data-validation-type="numeric"
data-validation-type="alphanumeric"
data-validation-type="date"
data-validation-type="email"
data-validation-type="dropdown"

Dropdowns are valid only if they contain a non-null value.

Note that this validation snippet comes from a custom solution implemented for a custom project. You will need CSS styling for all classes mentioned above. Feel free to customize it as you see fit and, if you wish, share the code.

Find more JavaScript tutorials, code snippets and samples here.

Related posts

Leave a Reply