Skip to content Skip to sidebar Skip to footer

Javascript Multiple Events

I'm doing a form, and I did a form validation that checks every part of the form but when I need to do multiple errors the code gets really long, the best way will be to use a smal

Solution 1:

Many code lines is not always a bad thing. You are not writing bad code.

Somethings you can do a little cleaner IMO:

  • finame == null || finame == "" can be written as !finame
  • document.getElementById("perror") can be stored in a variable to speed things up.

The code you are writing has been done alot by many people and library's. Try to see how they do it and learn from it.

Solution 2:

Instead of hardcoding every single posibility you could do the following:

  1. Add a class to all the inputs that you want to check.
  2. Make a for-loop that iterates through every element that has your specific class
  3. For each element you check if it has been set. If it has not been set, then you print the name of the element and tell the user it was not set.

This way you only have to write the code once.

EDIT: Also you don't have to worry about adding more input elements this way. You just add the class to the new element and the for-loop will also check the newly added input field.

If this seems to cumbersome for you; then you could always try to search on google for a javascript input field validation plugin

Solution 3:

As long as each field has a corresponding label with the for attribute pointing to the associated input's id attribute (good practice), you could do something like this:

functionvalidateForm() {
    var required = ['firstname', 'lastname'];
    var i;
    var elCurrent;
    var elLabel;
    var strLabel;
    var errFields = [];
    var errMsg    = '';

    // condensed reverse loop.  Faster for large arrays.  Not really needed in this case, but force of habit.for( i = required.length; --i >= 0; ){
        elCurrent = document.getElementById(required[i]);

        if( elCurrent.value.length <= 0 ){
            elLabel  = document.querySelector('label[for=' + required[i] + ']');
            strLabel = elLabel.textContent || elLabel.innerText;

            errFields.push(strLabel);
        }
    }

    if( errFields.length > 0 ){
        errMsg = errFields.join(" and ") + ' may not be blank.';

        document.getElementById("perror").innerHTML = errMsg;
    }
}

You could also use the HTML5 required attribute to either use built-in browser validation, or, in browsers that don't support it, you can also use that attribute to grab the list of required fields, rather than hard-coding an array like I did.

If you don't want to use HTML5 required, then you can use some other attribute (like data-required perhaps, or a classname) and either loop through, or use something like querySelectorAll (don't forget to polyfill or provide a workaround for non-supporting browsers, such as IE8 and below)

Solution 4:

You could shorten your code by writing a function validationFailed and a isFieldEmpty function like this:

var formValid = true;
functionvalidationFailed(message) {
    document.getElementById("perror").innerHTML = message;
    formValid = false;
}    
functionisFieldEmpty(field) {
    return field == null || field== "";
}

Then you can do the validation like the following:

function validateForm() {
    formValid = true;

    if (isFieldEmpty(finame) && isFieldEmpty(laname)) validationFailed("First name and last name were not filled!");
    elseif (isFieldEmpty(finame)) validationFailed("First name was not filled!");
    elseif (isFieldEmpty(laname)) validationFailed("Last name was not filled!");

    [...] // More validationsreturn formValid;
}

This would reduce your lines of code significantly. Try to prevent writing redundant code as much as possible

Solution 5:

Well I would suggest this code if you want to perform same validation on all 7 fields. For example 3 fields to validate.

functionValidationFunction()
{
   var message = '';
   varFields = newArray("fname","lname","midname"); //id of fieldsvarFullNames = newArray("First Name","Last Name","Mid Name");//Fields' fullnamesfor(var i=0; i<3; i++)
   {
       if(document.forms["myForm"][Fields[i]].value == "")
       {
            message += ', '+FullNames[i];
       }
   }
   document.getElementById("perror").innerHTML = message.substring(2)+' are empty';
}

Off course this code can be moderated in more better way as per requirement.

Post a Comment for "Javascript Multiple Events"