Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 462
  • Last Modified:

How can I conditionally validate controls on my form using jquery plug in

I'm trying to implement some conditional validation on my web form but it's not working as needed.  I have 3 text boxes on my form, first, last name and company.  If the first and last name are populated then company isn't required and if company has been populated first and last name aren't required.
 
With the code I have right now, if the form is submitted with all 3 fields blank, messages that the fields are required appears which is perfect but if the first and last name are populated company still shows as being required.  The same thing happens if company is populated, first and last name still show required error message.

I'm assuming the required rule needs to be removed from whichever control is no longer required but I can't figure out how to do this so I'm stuck.

<script type="text/javascript">
        $(document).ready(function () {
            var firstNameCtrl = $('#<%= addressInfo.FirstNameClientID %>');
            var lastNameCtrl = $('#<%= addressInfo.LastNameClientID %>');
            var companyNameCtrl = $('#<%= addressInfo.CompanyClientID %>');
            firstNameCtrl.focus();

            var validator = $('#form1').validate({
                highlight: function (element, errorClass) {
                    $(element).addClass("invalidElem");

                },
                unhighlight: function (element, errorClass) {
                    $(element).removeClass("invalidElem");

                },
                errorElement: "div",
                errorClass: "errorMsg"
            });

            $.validator.addClassRules({
                nameValidation: {
                    required: function (element) {
                        return $(companyNameCtrl).val() == '';
                    } //end required
                }, //end nameValidation
                companyValidation: {
                    required: function (element) {
                        return $(firstNameCtrl).val() == '' && $(lastNameCtrl).val() == '';
                    } //end required
                } //end company validation
            }) //end nameValidation

            $(firstNameCtrl).add(lastNameCtrl).addClass("nameValidation").change(function (e) {
                $('form').validate().element($(e.target));
            });
            $(companyNameCtrl).addClass("companyValidation").change(function (e) {
                $('form').validate().element($(e.target));
            });


        });           //end ready
    </script>

Open in new window

0
obb-taurus
Asked:
obb-taurus
  • 9
  • 9
2 Solutions
 
designatedinitializerCommented:
you do it by using the methods rules("add", { whatever} ); and rules("remove", {whatever} );
Like this:

$(companyNameCtrl).rules("remove", "required");

$(companyNameCtrl).rules("add", {required: true});

Open in new window


But you'll have to update that in some event.
I would update the rules onFocus, in the 1s and 2nd fields, 'cause those determine the outcome.
0
 
obb-taurusAuthor Commented:
designatedinitializer,

I should have mentioned that I'm fairly new to jQuery and I'm having a bit of a problem following your your suggestion, could you provide a small example of your solution?

Thanks
0
 
designatedinitializerCommented:
turns out it is even simpler.
Make your rules for the companyNameCtrl like this:

rules: {
    details: {
      required: "#firstNameCtrl:filled, #lastNameCtrl:filled"
    }
}

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
obb-taurusAuthor Commented:
designatedinitializer,

Is it ok for me to slide this in where I'm currently specifiying the rules in the .addClassRules?  Second question is that firstNameCtrl and lastNameCtrl are actually variables, how would I write the correct syntax?

Thanks
0
 
designatedinitializerCommented:
1. Yes
2.
$("#id_of_the_element")

..replace with the proper id's
0
 
obb-taurusAuthor Commented:
I put the code in but it unfortunately still does not work.  I may not be understanding the code you provided

required: "#firstNameCtrl:filled, #lastNameCtrl:filled"

The way I read this is if firstNameCtrl is filled and lastNameCtrl is filled then it will return true, is that correct?  If so, it would have to be the opposite, if firstNameCtrl and lastNameCtrl are not filled, it would have to return true cause I need to have first and last name required if company is not filled in and vice verse.

The code I initially posted passed validation with the exception that if for example a company name was entered, the first and last name still showed as being required but when the form was submitted it worked.  I'm attaching a couple images which may help illustrate my problem a little better.  One image show what happens when the form is submitted with nothing entered, the second shows what happens when the company name is entered.  I need to get rid of the messages and coloring in the first and last name fields.Image with no fields completed and form has been submittedCompany field filled in but first and last still showing as required
0
 
designatedinitializerCommented:
You're right!
I was giving you the opposite rule!
It should be
required: "#firstNameCtrl:blank, #lastNameCtrl:blank"

that way, the said field will be required when both #firstNameCtrl and #lastNameCtrl are left blank.
0
 
obb-taurusAuthor Commented:
I agree, that will probably do the trick for the validation but will it remove the error messages?  In the case of the second image attached to my previous post, the company name was entered but the first and last name elements still had error messages.  In actuality the problem all along has been the error messages, the validation worked but I need to know how to remove the errorElement and errorClass from the validation on the first and last name controls.

Thanks
0
 
designatedinitializerCommented:
the jquery validation plugin should take care of that.
0
 
obb-taurusAuthor Commented:
As suspected, the :blank did work but still having the problem that the error message doesn't clear.  I'll post the most recent validation code, perhaps you may be able to see something that I may be doing wrong.

var validator = $('#form1').validate({
                highlight: function (element, errorClass) {
                    $(element).addClass("invalidElem");

                },
                unhighlight: function (element, errorClass) {
                    $(element).removeClass("invalidElem");

                },
                errorElement: "div",
                errorClass: "errorMsg"
            });

            $.validator.addClassRules({
                nameValidation: {
                    required: "#<%= addressInfo.CompanyClientID %>:blank"
                }, //end nameValidation
                companyValidation: {
                    required: "#<%= addressInfo.FirstNameClientID %>:blank, #<%= addressInfo.LastNameClientID %>:blank"
                } //end company validation
            }) //end nameValidation

            $(firstNameCtrl).add(lastNameCtrl).addClass("nameValidation").change(function (e) {
                $('form').validate().element($(e.target));
            });
            $(companyNameCtrl).addClass("companyValidation").change(function (e) {
                $('form').validate().element($(e.target));
            });
0
 
designatedinitializerCommented:
Try adding this line inside those two change handlers at the bottom of your script, like this:

validator.showErrors({"firstNameCtrl": "", "lastNameCtrl": "", "companyNameCtrl": "", });
0
 
obb-taurusAuthor Commented:
I added the lines as you suggested and if I run it under Firefox nothing happens and if I run it under IE 9, I get the following error message:

Unable to get value of the property 'name': object is null or undefined
0
 
designatedinitializerCommented:
Here's a sample I made for you.
This validates exactly like you want it.
Just mix+match with the rest of your code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Validation</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function () {
  $('#form1').validate({
	rules: {
				FirstNameClient: {required: "#CompanyClientID:blank"},
				LastNameClientID: {required: "#CompanyClientID:blank"},
				CompanyClientID: {required: "#firstNameCtrl:blank, #lastNameCtrl:blank"},
			}
  });
});           //end ready
</script>
<style>
  input { border: 1px solid black; margin-bottom: .5em;  }
	label.error {
		display:none;
		background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
		padding-left: 16px;
		margin-left: .3em;
	}
	label.valid {
		background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
		display: block;
		width: 16px;
		height: 16px;
	}
</style>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<label for="FirstNameClient" >First name<input type="text" name="FirstNameClient" id="FirstNameClient" /></label><br/>
<label for="LastNameClientID">Last name<input type="text" name="LastNameClientID" id="LastNameClientID"/></label><br/>
<label for="CompanyClientID">Company<input type="text" name="CompanyClientID" id="CompanyClientID"/></label><br/>
<input type="submit"/>
</form>
</body>
</html>

Open in new window

0
 
obb-taurusAuthor Commented:
Thanks for the code, I do however have one question.  The first, last and company names are ASP.NET textboxes which I know render as input elements in HTML but there is another hitch, they are inside a user control so can you tell me how I reference the name element in the rules for this scenario?

Thanks
0
 
designatedinitializerCommented:
It's simple enough to find out: load the page in your browser, then "View source".
Whatever appears inside the HTML id for those <input> elements, that is what you need.
0
 
obb-taurusAuthor Commented:
Gave the code you provided a try and it still didn't work in my situation but I was able to find a solution which seems to accomplish what I want, all I did was add $('#form1').valid() in each of my change statements and that seemed to do the trick.  This solutions seems to make sense because there is a change being made to the validation and in order to check all other elements with validation the form needs to be revalidated, what do you think?

$(firstNameCtrl).add(lastNameCtrl).addClass("nameValidation").change(function (e) {
                $('#form1').validate().element($(e.target));
                $('#form1').valid();

            });
            $(companyNameCtrl).addClass("companyValidation").change(function (e) {
                $('#form1').validate().element($(e.target));
                $('#form1').valid();
            });
0
 
designatedinitializerCommented:
i think you're right on. just try!
0
 
obb-taurusAuthor Commented:
Thanks for all your help
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 9
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now