2

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 small example. I have these two input lines:

  First Name: <input type="text" id="firstname" name="fname"/>
<p id="firsterror"></p>
Last Name: <input type="text" id="lastname" name="lname" />
<p id="lasterror"></p>

Now, the form will go to the function when I submit it, and the function will be like that for example:

function validateForm() {
    var finame = document.forms["myForm"]["fname"].value;
    var laname = document.forms["myForm"]["lname"].value; 
if ((finame == null || finame == "") && (laname == null || laname == "")) {
        document.getElementById("perror").innerHTML = "First name and last name were not filled!";
        return false;
    }
    else if (finame == null || finame == "") {
        document.getElementById("perror").innerHTML = "First name was not filled!";
        return false;
    }
    else if (laname == null || laname == "") {
        document.getElementById("perror").innerHTML = "Last name was not filled!";
        return false;
    } 
else { return true; } }

Now as you can see there are 3 errors that can happen, when first name is unfilled, last name is unfilled and both are unfilled, now this is just a piece of the code but in the full code I have 7 variables that needs to be checked and this means I need to write a code for all things that can happen for example all vars are unfilled, vars 1-7, vars 2-7, vars 3-7, vars 4-7... and then all the options of 6 vars together and than 5, etc.. This can get too long and someone told me there's such thing that does those options without writing some many code lines, sorry for bad english and bad explainning. thanks in advance :)

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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:

function validateForm() {
    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)

Comments

0

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

var formValid = true;
function validationFailed(message) {
    document.getElementById("perror").innerHTML = message;
    formValid = false;
}    
function isFieldEmpty(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!");
    else if (isFieldEmpty(finame)) validationFailed("First name was not filled!");
    else if (isFieldEmpty(laname)) validationFailed("Last name was not filled!");

    [...] // More validations

    return formValid;
}

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

Comments

0

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

function ValidationFunction()
{
   var message = '';
   var Fields = new Array("fname","lname","midname"); //id of fields
   var FullNames = new Array("First Name","Last Name","Mid Name");//Fields' fullnames
   for(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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.