DEV Community

Ciprian Popescu
Ciprian Popescu

Posted on

Quick tutorial: JavaScript Form Validation

JavaScript Form Validation

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

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

Match an element against a given value:

function cgValueMatch(e) {
    return (e.value !== '') ? true : false;
}
Enter fullscreen mode Exit fullscreen mode

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

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');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, custom data validation needs some additional HTML parameters and an onload() event.

Read more about custom JavaScript form validation and implementation on my development blog.

Top comments (0)