0

I am trying to validate my form that is a jQuery show/hide form. jQuery validate plugin only validates my last input on the last div (input type file). I can currently upload an image and submit the form successfully with the remaining inputs empty.

Below is the third div and when i click post ad with no inputs filled in, "This field is required" is shown. Third Div

Below is the first div with no validation messages First Div

Below is the second div with no validation messages Second Div

Here is my form:

<!DOCTYPE html>
<html lang="en">

<head>

   <title>Zootopia</title>

   <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

   <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

</head>

<body>

<form id="ad_form" method="post">

  <div id="ad_form_section1">

    <div class="form-group">
       <label for="ad_title">Ad Title</label>
       <input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
    </div>

    <div class="form-group">
       <label for="description">Describe what you're offering</label>
       <textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
    </div>

  <button type="button" id="ad_section2" class="btn btn-primary"> Next </button>

  </div>

  <div id="ad_form_section2">

    <div class="form-group">
       <label for="location"> Location</label>
       <input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
    </div>

    <div class="form-group">
       <label for="price">Price</label>
       <input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
    </div>

   <button type="button" id="back_section1" class="btn btn-primary"> Back </button>

   <button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
  </div>

  <div id="ad_form_section3">

    <div>
       <label> Select pet pictures</label>
       <input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
    </div>

    <button type="button" id="back_section2" class="btn btn-primary"> Back </button>

    <input type="hidden" name="action_type" value="add" />

    <input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />

  </div>

</form>

Here is my JavaScript:

$(document).ready(function(){

  $("#ad_section2").click(function(){
      $("#ad_form_section1").hide();
      $("#ad_form_section2").show();
  });

  $("#back_section1").click(function(){
      $("#ad_form_section1").show();
      $("#ad_form_section2").hide();
  });

  $("#ad_section3").click(function(){
      $("#ad_form_section3").show();
      $("#ad_form_section2").hide();
  });

  $("#back_section2").click(function(){
      $("#ad_form_section2").show();
      $("#ad_form_section3").hide();
  });

    $("#ad_form").validate({
        rules:{
              ad_title:{
                required: true
              },
              description:{
                required: true
              },
              location:{
                required: true
              }
        },
        messages:{
              ad_title: {
                required: "please enter an ad title"
              },
              description: {
                required: "please enter a description"
              },
              location: {
                required: "please enter a location"
              }
        },
            submitHandler: function(form) {
              var petID = $( "#pet_ad option:selected" ).val();
              var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;

                   $(form).ajaxSubmit({
                      url:addAdUrl,
                      type:"post",
                      datatype: 'json',
                      success: function(result){
                          if(result.petAd == false){
                            alert("Pet ad already exists!");
                          }else{
                            alert("Ad posted!");
                            $('#image_table').hide();
                          }
                      },
                      error: function(error) {
                        alert("Error");
                      }
                  });
            }
      });
})

Here is my CSS:

#ad_form_section2,
#ad_form_section3{
  display: none;
}
Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
Jessica
  • 167
  • 1
  • 2
  • 11
  • Any questions about how to use Stack Overflow and its features/functions should only be asked on the [SO Meta site](https://meta.stackoverflow.com/). – Sparky May 24 '18 at 02:17
  • You should be editing or closing your original question before posting it again. Thank you. – Sparky May 24 '18 at 15:29
  • @Sparky as i said i am very new to asking questions on stack overflow so I didn't actually know i can go and edit/delete a question that has already been posted. i'll keep this in mind for next time! – Jessica May 25 '18 at 02:19
  • @Sparky: The earlier question has been automatically deleted. Would it make sense to reopen this one? – Ilmari Karonen May 27 '19 at 14:01

2 Answers2

1

By default the plugin is going to ignore any/all fields that are hidden. You have to set to the ignore option to "nothing".

$("#ad_form").validate({
    ignore: [],  // ignore nothing, validate everything
    rules:{
        ad_title:{ ....

If you're expecting validation when you show/hide sections of the form, that's not how it works. You're going to have to programmatically trigger validation on the relevant fields as you click back and forth. Use the .valid() method for this.

However, multi-step validation can quickly get tedious so you may have to re-think your entire approach. I personally like to enclose each section within its own set of <form></form> tags so I can control validation on each step separately.

Here's one example:

https://stackoverflow.com/a/20481497/594235

Sparky
  • 98,165
  • 25
  • 199
  • 285
1

You need to add a condition before you show/hide next fields

if ( $('field-id').valid() ) {
     // Code 
}

For example:

$("#ad_section2").click(function(){
   if ($('#ad_title').valid() && $('#description').valid()) {
      $("#ad_form_section1").hide();
      $("#ad_form_section2").show();
    }
});

Also, don't forget to set character encoding to avoid characters range error, Add the following code just below <head> tag:

<meta charset="UTF-8">

Form Example:

$(document).ready(function(){

  $("#ad_form").validate({
    rules:{
      ad_title:{
        required: true,
        minlength: 3, // set minimum title length
      },
      description:{
        required: true,
        minlength: 10,
      },
      location:{
        required: true
      }
    },
    messages:{
      ad_title: {
        required: "please enter an ad title",
        minlength: "Your title must be more than 3 characters!",
      },
      description: {
        required: "please enter a description",
         minlength: "Your description must be at least 10 characters long",
      },
      location: {
        required: "please enter a location"
      }
    },
    submitHandler: function(form) {
      var petID = $( "#pet_ad option:selected" ).val();
      var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;

      $(form).ajaxSubmit({
        url:addAdUrl,
        type:"post",
        datatype: 'json',
        success: function(result){
          if(result.petAd == false){
            alert("Pet ad already exists!");
          }else{
            alert("Ad posted!");
            $('#image_table').hide();
          }
        },
        error: function(error) {
          alert("Error");
        }
      });
    }
  });

  $("#ad_section2").click(function(){
    // Check if valid before show/hide
    if ($('#ad_title').valid() && $('#description').valid()) {
      $("#ad_form_section1").hide();
      $("#ad_form_section2").show();
    }
  });

  $("#back_section1").click(function(){
    $("#ad_form_section1").show();
    $("#ad_form_section2").hide();
  });

  $("#ad_section3").click(function(){
  // Check if valid before show/hide
    if ($('#location_ad').valid()) {
      $("#ad_form_section3").show();
      $("#ad_form_section2").hide();
    }
  });

  $("#back_section2").click(function(){
    $("#ad_form_section2").show();
    $("#ad_form_section3").hide();
  });
});
#ad_form_section2,
#ad_form_section3 {
  display: none;
}
label.error {
  color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

<div class="container">
  <form id="ad_form" method="post">

    <div id="ad_form_section1">
      <div class="form-group">
        <label for="ad_title">Ad Title</label>
        <input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
      </div>
      <div class="form-group">
        <label for="description">Describe what you're offering</label>
        <textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
      </div>
      <button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
    </div>

    <div id="ad_form_section2">
      <div class="form-group">
        <label for="location"> Location</label>
        <input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
      </div>
      <div class="form-group">
        <label for="price">Price</label>
        <input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
      </div>
      <button type="button" id="back_section1" class="btn btn-primary"> Back </button>
      <button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
    </div>

    <div id="ad_form_section3">
      <div>
        <label> Select pet pictures</label>
        <input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
      </div>
      <button type="button" id="back_section2" class="btn btn-primary"> Back </button>
      <input type="hidden" name="action_type" value="add" />
      <input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
    </div>

  </form>
</div>

More examples from documentation

awran5
  • 4,333
  • 2
  • 15
  • 32
  • thanks for your help! i managed to get the validation functioning but now my ajax is not recognising my input values in form 1 and form 2. I know i need to change my php processing file but unsure how. – Jessica May 24 '18 at 03:07
  • Do you have any log error? Please follow these examples [here](https://gist.github.com/jakebellacera/839163) and [here](https://stackoverflow.com/questions/41361231/submit-form-with-ajax-and-jquery-validation) – awran5 May 24 '18 at 04:04
  • i just looked at those examples and attempted them to no avail haha i think i need to see the PHP file as I think I am passing the data incorrectly into ajax – Jessica May 24 '18 at 04:45