0

I have function that checks if fields are blank but if all fields are blank it only shows one of the validation message's, I think this is because I have used an if statement:

          function validateForm()
        {
         var sName=document.forms["myForm"]["surname_5"].value;
         if (sName==null || sName=="")
       {
           document.getElementById("sNameMessage").innerHTML = "*Surname is required";
           return false;
       }
          var x=document.forms["myForm"]["firstname_4"].value;
           if (x==null || x=="")
        {
          document.getElementById("fNameMessage").innerHTML = "*First name is required";
          return false;
        }
       var y=document.forms["myForm"]["selectid"];
         if(y.options[y.selectedIndex].value == "Title")
       {
      document.getElementById("titleMessage").innerHTML = "You need to select a title";
      return false;
      }


      } 

How do I get it so all validation messages show if the user has left all fields blank?

2 Answers 2

3

Don't return false immediately. Set a variable to false (after defining it as true at the very start of the function) and return that variable at the end.

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

Comments

0

Try something like this (or add all your code if you need more details)

JavaScript:

function validateForm() {
    var sName = document.forms["myForm"]["surname_5"].value;
    var ret = true;
    if (sName == null || sName == "") {
        document.getElementById("sNameMessage").innerHTML = "*Surname is required";
        ret = false;
     }
     var x = document.forms["myForm"]["firstname_4"].value;
     if (x == null || x == "") {
         document.getElementById("fNameMessage").innerHTML = "*First name is required";
         ret = false;
     }
     var y = document.forms["myForm"]["selectid"];
     if (y.options[y.selectedIndex].value == "Title") {
         document.getElementById("titleMessage").innerHTML = "You need to select a title";
         ret = false;
     }
     return ret;
}

3 Comments

Thank you, it does show the messages for a second but then post's back to the server?
I don't understand your comment this is a question or an affirmation ? and please add some code if you want help.
Your solution is not fully working, as it shows the message's but than post's back to the server anyway. Should I change this onsubmit="validateForm(); return false;?

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.