Using JavaScript To Validate Form Input Values

While developing the new version of BonLook.com, I needed a way to validate user input values in the various forms of the site. I wanted to avoid using yet another jQuery library.

I came up with a simple function named validateUserInput taking 5 arguments:

  1. contentToValidate: the actual text that was entered by the user;

  2. validationType: the type of validation, I have three so far:

    1. different: user input is different from a specific string (mostly for fields left empty by the user);

    2. same: user input matches something specific (useful form password confirmation field);

    3. email: user input is a valid email address.

  3. validationRule: what user input will be compared against;

  4. elementToValidate: element that will receive the invalid message (if any);

  5. invalidMessage: the message that I want displayed near the validated field.

Here is the function:


function validateUserInput(contentToValidate, validationType, validationRule, elementToValidate, invalidMessage) {
    $(elementToValidate).prev('.error').remove();
    var userInputValid = false;
    if (validationType == "different") {
        if (contentToValidate !== validationRule) {
            userInputValid = true;
        }
    } else if (validationType == "same") {
        userInputValid = (contentToValidate == validationRule);
    }  else if (validationType == "email") {
        userInputValid = isValidEmailAddress(contentToValidate);
    }       
    if (userInputValid == true) {
        toggleValidityClass(true, elementToValidate);
        return true;
    } else {
        toggleValidityClass(false, elementToValidate);
        var errorElement = $('<div />', {
            class: 'error',
            html: invalidMessage
        });
        $(elementToValidate).before(errorElement);
        return false;
    }
}

And here is toggleValidityClass which adds/removes a red border to the validated form field using a CSS class:


function toggleValidityClass(isValid, identifier) {
    if (isValid) {
        $(identifier).removeClass('invalid');
    }
    else {
        $(identifier).addClass('invalid');
    }
}

Upon form submission, you could validate the password and confirmpassword inputs like this:


if (
    validateUserInput($('#my-form').find('[name=password]').val(), "different", "", $('#my-form').find('[name=password]'), "You must provide a password") &
    validateUserInput($('#my-form').find('[name=confirmpassword]').val(), "same", $('#my-form').find('[name=password]').val(), $('#my-form').find('[name=confirmpassword]'), "Password must match")
   ) {
    // inputs valid, proceed
}