0

I have a simple form consisting of 3 input fields. All inputs are required. I have set the form's 'onsubmit' attribute to 'return validateForm()'. Within this function, I am doing the form validation. I have it working so far so that if all fields are empty, the error spans are displayed. Getting the individual errors to come up with the appropriate fields is the part I'm having trouble with. Basically, if I leave 2 fields empty, only one error message comes up. I want it so that no matter what fields are empty, the appropriate error messages appear.

Here is my code:

HTML:

<form id="contactForm" action="contact.php" method="post" onsubmit="return validateForm()">
    <div>
        <input type="text" name="name" id="name" placeholder="Your Name"  maxlength="65" tabindex="1">
        <label for="name">Name</label>
        <span class="error" id="fname">Please tell me your name.</span>
    </div>
    <div>
        <input type="email" name="_replyto" id="email" placeholder="Your Email"  tabindex="2">
        <label for="email">Email</label>
        <span class="error" id="yourEmail">Please tell me your email address.</span>
    </div>
    <div>
        <textarea name="message" id="message" rows="10" placeholder="Your Message..." maxlength="500" tabindex="3" ></textarea>
        <label for="message">Your Message</label>
        <span class="error" id="yourMessage">Please leave me a message.</span>
    </div>
    <div>
        <input type="submit" value="Send" tabindex="4">
    </div>
</form>

Javascript:

function validateForm() {
    var name = document.forms["contactForm"]["name"].value;
    var email = document.forms["contactForm"]["_replyto"].value;
    var message = document.forms["contactForm"]["message"].value;

    if ((name == null || name == "") && (email == null || email == "") && (message == null || message == "")) {
        $(".error").show();
        return false;
    } else if (name == null || name == "") {
        $("#fname").show();
        return false;
    } else if (email == null || email == "") {
        $("#yourEmail").show();
        return false;
    } else if (message == null || message == "") {
        $("#yourMessage").show();
        return false;
    } else {
        //submit form
        return true;
    }
}

Once the function returns true, am I right in saying that the form will then submit via the contact.php file?

Thanks in advance.

Forrest
  • 107
  • 2
  • 4
  • 16

3 Answers3

1
function validateForm() {
  var name = $('#name').val(), email = $('#email').val(),
      message = $('#message').val();

  $('.error').hide();

  if (!name)  $("#fname").fadeIn();
  if (!email) $("#yourEmail").fadeIn();
  if (!message) $("#yourMessage").fadeIn();

  return $('.error:visible, .error:animated').length == 0;
}

It can be even shorter and more unified

function validateForm() {
  $('.error').hide();
  $('textarea, input[type=text]').each(function() {
     if (!$(this).val())
        $(this).siblings('.error').fadeIn();    
  });
  return $('.error:visible, .error:animated').length == 0;
}
Cheery
  • 16,063
  • 42
  • 57
  • Thank you, this works really well. Exactly what I wanted. Just wondering though, where do I now put return true for the function so that the email sends? – Forrest Sep 29 '14 at 22:34
  • @Forrest I provided even better example. Not sure what you are asking - if validateForm returns true then the form is submitted to contact.php script. – Cheery Sep 29 '14 at 22:36
  • I've just tried the second example. If I click the send button with all fields empty, the email error doesn't appear? I was asking if I needed to actually put `return true` somewhere in the function? Are you saying that if all fields are field in correctly, it will automatically do that then? Sorry, I'm new to forms and PHP. Thanks again. – Forrest Sep 29 '14 at 22:40
  • At the moment, if all fields are completed, you have to press the send button twice. The first time, it fades out the errors, then, after a second press it will submit the form. Is there a way to do it so that the form submits straight away? – Forrest Sep 29 '14 at 22:42
  • @Forrest yes, otherwise function returned `undefined`, which is not `true`, but 'more' `false`. This return will go to return in onSubmit and form will not be submitted. – Cheery Sep 29 '14 at 22:42
  • @Forrest replace `.fadeOut()` with `.hide()` – Cheery Sep 29 '14 at 22:44
  • Sorry to bug you again. I'm trying to validate the email in your script. I'm using this: `var atpos = x.indexOf("@"); var dotpos = x.lastIndexOf("."); if (atpos< 1 || dotpos=email.length) { $("#yourEmailValid").fadeIn(); }` Placing it in your script is causing issues. Any idea at all as to what I could do? Thanks again. – Forrest Sep 29 '14 at 23:30
  • @Forrest it is better to validate email with regular expression or, if you are using HTML5, with `type="email"`. Look here http://stackoverflow.com/questions/2507030/email-validation-using-jquery – Cheery Sep 29 '14 at 23:35
  • Ok great. I know about the html5 type but I just want to do it for browsers that don't support it. That page you linked looks good. Would I just place that function within the validateForm() function? – Forrest Sep 29 '14 at 23:52
  • @Forrest Function can be within validateForm or global (just not inside of another function). – Cheery Sep 29 '14 at 23:53
  • Thanks again. I've got it working I think. I added a variable at the top of the validateForm function like so: `var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;` and then changed the email line of code to the following: `if (!email || !regex.test(email)) $("#yourEmail").fadeIn();`. – Forrest Sep 30 '14 at 00:00
0

Instead of returning false as soon as you discover an issue - set a flag - the return false; prevents the rest of your code to execute and your error message isn't shown.

function validateForm() {
    var name = document.forms["contactForm"]["name"].value;
    var email = document.forms["contactForm"]["_replyto"].value;
    var message = document.forms["contactForm"]["message"].value;

     var allFilled = true;

if ((name == null || name == "") && (email == null || email == "") && (message == null || message == "")) {
    $(".error").show();
    allFilled =  false;
} else if (name == null || name == "") {
    $("#fname").show();
    allFilled =  false;
} else if (email == null || email == "") {
    $("#yourEmail").show();
    allFilled =  false;
} else if (message == null || message == "") {
    $("#yourMessage").show();
    allFilled =  false;
} 
return allFilled;

}

Birgit Martinelle
  • 1,869
  • 1
  • 12
  • 9
0

To answer your question, yes once all of the if clauses fail, it will hit the else clause and return true.

I would suggest one refinement thought. if (name == null || name == "") can be rewritten if (!name).

So:

function validateForm() { var name = document.forms["contactForm"]["name"].value; var email = document.forms["contactForm"]["_replyto"].value; var message = document.forms["contactForm"]["message"].value;

    if (!name && !email && !message) {
        $(".error").show();
        return false;
    } else if (!name) {
        $("#fname").show();
        return false;
    } else if (!email) {
        $("#yourEmail").show();
        return false;
    } else if (!message) {
        $("#yourMessage").show();
        return false;
    } else {
        //submit form
        return true;
    }
}
manishie
  • 5,302
  • 1
  • 20
  • 21