Link to home
Start Free TrialLog in
Avatar of obb-taurus
obb-taurusFlag for Canada

asked on

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

Avatar of designatedinitializer
designatedinitializer
Flag of Portugal image

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.
Avatar of obb-taurus

ASKER

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
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

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
1. Yes
2.
$("#id_of_the_element")

..replace with the proper id's
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.User generated imageUser generated image
SOLUTION
Avatar of designatedinitializer
designatedinitializer
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
the jquery validation plugin should take care of that.
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));
            });
Try adding this line inside those two change handlers at the bottom of your script, like this:

validator.showErrors({"firstNameCtrl": "", "lastNameCtrl": "", "companyNameCtrl": "", });
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
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

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
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.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i think you're right on. just try!
Thanks for all your help