1

I am working on java script and i am stuck on one phase. In my project i have to validate all fields when the form is submitted and display error message on same page in order list above the form field. bellow is my code

function validation(){
    var errorMsg=new Array(); 
    //var errorMsg = "";
    if(document.getElementById("fullname").value = " "){
        errorMsg[0] = "Please Enter Full Name\n"
}
if(document.getElementById("street").value = " "){
        errorMsg[1]= "Please Enter Street Name\n"
}
if(document.getElementById("postcode").value = " "){
        errorMsg[2]= "Please Enter Postlecode\n"
}
if(document.getElementById("phone").value = " "){
        errorMsg[3]= "Please Enter Phone Number\n"
}
if(document.getElementById("email").value = " "){
        errorMsg[4]= "Please Enter Email Id\n"
}
if(errorMsg!=" "){
    var r =" ";
    for(var i=0;i<=errorMsg.length-1;i++){
    document.getElementById("error").innerHTML="<li>"+errorMsg[i]+"</li>"
    }   
    return false;
}
}
</script>

when i run this code it gives me only last value

can anybody help me how to display error message on the top of the form?

3
  • Can you post your HTML part, that will be useful to solve the problem Commented Dec 5, 2012 at 6:39
  • for (...) { innerHTML = errorMsg[i]; } ಠ_ಠ Commented Dec 5, 2012 at 6:40
  • Tip : use equality operator (== ) instead of assignment(=) in if Commented Dec 5, 2012 at 6:44

7 Answers 7

3

You've got a mistake here:

document.getElementById("error").innerHTML="<li>"+errorMsg[i]+"</li>"

You need to append errorMsg, not to assign it. For example like this:

document.getElementById("error").innerHTML+="<li>"+errorMsg[i]+"</li>"

If you want to display the error message on the top of the page, you should create div, where you want, give to this div the id and set innerHtml to this div:

<div id="AllErrors"></div>

document.getElementById("AllErrors").innerHTML+="<li>"+errorMsg[i]+"</li>"

Also you could improve your validation and validate fields when a user is typing, not after he submitted all information.

And by the way, you add errors in tag <li>. So, you know that you should also add <ol> or <ul> to make a list?

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

Comments

1

I rewrote your code a bit. Here is what I changed:

  • Instead of checking that the value equals " ", I have used the ! operator.
  • I have used push on the array instead of appending by index. This means that there are no empty spots in your array. push adds an element to the end of the array, irrespective of the index.
  • I used a forEach loop on the array. This goes through all the enumerable elements, irrespective of how many there are.

So, the example:

JS

// This could be done on form submit, I used a button for the fiddle.
document.getElementById("button").onclick = function () {   
    var errorMsg = new Array();

    if(!document.getElementById("fullname").value){
        errorMsg.push("Please Enter Full Name");
    }

    if(!document.getElementById("street").value){
        errorMsg.push("Please Enter Street Name");
    }

    if(!document.getElementById("postcode").value){
        errorMsg.push("Please Enter Postal Code");
    }

    if(!document.getElementById("phone").value){
        errorMsg.push("Please Enter Phone Number");
    }

    if(!document.getElementById("email").value){
        errorMsg.push("Please Enter Email Id");
    }

    var messageHtml = "";

    errorMsg.forEach(function (message) {
        messageHtml += "<li>" + message + "</li>";
    });

    document.getElementById("error").innerHTML = messageHtml;
};

See this fiddle: http://jsfiddle.net/M48gA/

2 Comments

thanks for your reply i understand your code expect one thing what isfunction (message) can you please explain it little bit more?
errorMsg.forEach loops through each element in the errorMsg array. The anonymous function that is defined as a parameter to forEach is executed on each element in the array. This code is more robust than that which you posted because it fills the array dynamically instead of by using indexes, and then loops through the elements in the array again, not using indexes.
1

You need to append each error to the existing .innerHTML rather than overwriting the existing:

document.getElementById("error").innerHTML += "<li>"+errorMsg[i]+"</li>"
// note += instead of = here --------------^

Though can skip the loop altogether and just do this:

document.getElementById("error").innerHTML = "<li>"+errorMsg.join("</li><li>")+"</li>";

(The .join() method puts all the array elements into a string separated by the specified text.)

Also, if only some of your conditions are met your array will have undefined (missing) elements since you are explicitly setting specific indexes, which means you'll be adding <li> elements with "undefined" displayed in them. You should do this instead:

    errorMsg.push("Please Enter Full Name\n");
    // OR
    errorMsg[errorMsg.length] = "Please Enter Full Name\n";

...either of which will add to the end of the array. Then to test if there were any errors do:

if (errorMsg.length > 0)

Also the conditions in your if statements are all doing assignments because they use = where they should use === (or ==), and you are testing whether each field contains a single space: " " where I think you want to test if each field is empty by comparing to an empty string: "".

Comments

0

You have to use === or == instead of = in if statement.

Comments

0

That's because innerHtml of "error" always gets replaced.So only last value is showed.

Try below link

Is it possible to append to innerHTML without destroying descendants' event listeners?

Comments

0

= is the assignment operator. In your if statements, you must use equal to == or exactly equal to === (checks type also).

You also need to use the add to existing operator += in your statement listing:

if(document.getElementById("fullname").value == " "){
    errorMsg[0] = "Please Enter Full Name\n"
}
if(document.getElementById("street").value == " "){
    errorMsg[1]= "Please Enter Street Name\n"
}
if(document.getElementById("postcode").value == " "){
    errorMsg[2]= "Please Enter Postlecode\n"
}
if(document.getElementById("phone").value == " "){
    errorMsg[3]= "Please Enter Phone Number\n"
}
if(document.getElementById("email").value == " "){
    errorMsg[4]= "Please Enter Email Id\n"
}
for(var i=0;i<=errorMsg.length-1;i++){
    document.getElementById("error").innerHTML += "<li>"+errorMsg[i]+"</li>"
}  

Comments

0

I guess you can simply try appending the error message to label in each case.

Inserting in an array will put "undefined" value in an array. e.g If you put valid fullname then there won't be anything at errorMsg[0].If you put invalid street, errorMsg[1] will have an entry "Please Enter Street Name\n".

Now,when you are to submit the form, say with submit button you will get error message for invalid street but will get "undefined" for first place of an array.

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.