John Taylor
John Taylor

Reputation: 1517

javascript validate form check - echo out errors in form?

i have currently got a javascript code which validates my form and shows an error if a field is not completed. i also want to know how i could echo out the errors in the form so for instance if 'fname' is not filled in then this says 'You did not fill in fname' or if 'fname' and fcompany' are not filled in this says

You did not fill in fname 
you did not fill in fcompany 

Heres my html:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Company Name: <input type="text" name="fname">
Company Registration Number: <input type="text" name="fcompany">

heres my javascript:

<script>
function validateForm()
 {
 var x=document.forms["myForm"]["cname"].value;
 if (x==null || x=="")
   {
document.body.scrollTop = document.documentElement.scrollTop = 0;
   document.getElementById("alertBox").style.display='block';
   return false;
   }
 }
</script>

Upvotes: 0

Views: 131

Answers (1)

MrCode
MrCode

Reputation: 64536

Have your validate function build an array of errors, then have another function take the errors array and build the HTML:

http://jsfiddle.net/J9LJj/

function displayErrors(errors){
    var container = document.getElementById("alertBox");
    var html = "<ul>";

    for(var i=0; i<errors.length; i++){
        html += "<li>" + errors[i] + "</li>";
    }
    html += "</ul>";

    container.innerHTML = html;
    container.style.display = "block";
}

function validateForm(){
    var fname = document.forms["myForm"]["fname"].value;
    var fcompany= document.forms["myForm"]["fcompany"].value;

    var errors = [];

    if(fname == ""){
        errors.push("you did not fill in fname");
    }
    if(fcompany == ""){
        errors.push("you did not fill in fcompany");
    }

    if(errors.length > 0){
        displayErrors(errors);
        return false;
    } else {
        return true;
    }
}

Upvotes: 1

Related Questions