I saw a post about someone trying to spread rules across multiple
pages.  The person was told to add rules dynamically, but there's no
way to add messages dynamically.  I'm wondering what you guys think
about this approach.

I had a situation where I wanted to reuse part of a form.  I think
this is a common enough pattern.  When a user registers for the first
time you want them to give you a username, a password and some
additional info.  Later the user might want to edit that additional
info so you present those fields again but now you don't have to
include the username and password field because you already know who
it is.

I broke out the "additional info" into its own file and included it
(through smarty in this case) into the form with the username and
password.  Of course I want the validation rules to be separate for
each piece and to live with the section it validates.

Unfortunately you cannot call jQuery("#MyForm").validate(options) more
than once and expect the rules to be combined.  You can add more rules
dynamically but you can't add messages that way.

Here's how got I around that.

In the subsection code (the "additional info" code) I put the
validation options into an object.  Then I check for the existence of
a javascript function that should be implemented in the enclosing
page.  If the function exists, I call it.  If the function doesn't
exist, I just call the normal validation code.

Here's the code from the included page:

<script type="text/javascript">

jQuery().ready(function() {

var options = {
   rules: {
     address: "required",
     city: "required",
     state: "required",
     zip_code: "required",
     phone: "required",
   },
   messages: {
     company_name: "Please enter your [Company Name]",
     address: "Please enter your [Address]",
     city: "Please enter your [City]",
     state: "Please enter your [State]",
     zip_code: "Please enter your [Zip Code]",
     phone: "Please enter your [Phone]",
   }
 };

 if (parent_validation_init){
    parent_validation_init(options);
 } else {
    jQuery("#MyForm").validate(options);
 }

}

</script>

Now in the parent html file, I implement
parent_validation_init(options) which takes the options object, adds
the new rules to the options object, and THEN call
jQuery("#MyForm").validate(options);

Here's what that code looks like:


<script type="text/javascript">

function parent_validation_init(options){
 options.rules["password_check"] = {equalTo: "#password"};
 options.messages["password_check"] = "Passwords must match";
 jQuery("#companyFormStepOne").validate(options);
}

jQuery().ready(function() {
 jQuery("#nextBtn").click(function() {
    jQuery("#companyFormStepOne").submit();
 });
});

</script>

Seems to work for me.  Any gurus see an issue with this?

Reply via email to