简体   繁体   中英

jquery form validation using groups

I have an order form, one part of the form is the address. It contains Company, Street-Address, ZIP, Town, Country with a simple jquery form validation with every field required, and ZIP validated for number. Now what I want is to group them and only have one field showing "valid address" on success, or "address wrong" on error.

This is a part of my js code:

$("#pageform").validate(
{
   messages: {
      company_from:     addressError, //addressError is a JS var for the error message
      street_from:      addressError,
      zip_from:         addressError,
      town_from:        addressError,
      country_from:     addressError
   },
   groups: {
      from:    "company_from  street_from  zip_from  town_from  country_from"
   },
   errorPlacement: function(error, element) {
      if (element.attr("name") == "company_from"
         || element.attr("name") == "street_from"
         || element.attr("name") == "zip_from"
         || element.attr("name") == "town_from"
         || element.attr("name") == "country_from"
         )
      {
         $("#error_from").append(error);
      }
   },
   success: function(label) {
      var attribute = $(label[0]).attr("for");
      $(".err-ok-" + attribute + " .ok").css("display", "block").css("visibility", "visible");
   }
}
);

This is a part of the corresponding HTML code:

<input type="text" name="company_from" id="company_from" class="required default input-s8" maxlength="255" />
<input type="text" name="street_from" id="street_from" class="required default input-s8" maxlength="255" />
<input type="text" name="zip_from" id="zip_from" class="required digits default input-s8" maxlength="5" onblur="checkCalculation()" />
<input type="text" name="town_from" id="town_from" class="required default input-s8" maxlength="255" />
<!-- and a select list for the country -->

You do not need to take a closer look on how I show the error and so on, my problem is, that I do not know when to show the error label and when the success label . When I enter a letter for the ZIP code, my errorPlacement function and the success function is called (and the errorPlacement first), so I guess it's always calling the success if there is at least one field correct.

Please ask if there are any questions, and I am pretty sure there are... :-)

Add rules

    rules: {
     company_from: "required",
     company_from: "required",
     zip_from: "required",
     town_from:"required",
     country_from:"required"
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM