Solved

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

Posted on 2012-03-26
18
444 Views
Last Modified: 2012-04-02
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
Comment
Question by:obb-taurus
  • 9
  • 9
18 Comments
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37768412
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
 

Author Comment

by:obb-taurus
ID: 37768802
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37768926
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
 

Author Comment

by:obb-taurus
ID: 37769014
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37769079
1. Yes
2.
$("#id_of_the_element")

..replace with the proper id's
0
 

Author Comment

by:obb-taurus
ID: 37769358
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
 
LVL 7

Assisted Solution

by:designatedinitializer
designatedinitializer earned 500 total points
ID: 37770581
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
 

Author Comment

by:obb-taurus
ID: 37771928
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37772014
the jquery validation plugin should take care of that.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 

Author Comment

by:obb-taurus
ID: 37772351
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37772889
Try adding this line inside those two change handlers at the bottom of your script, like this:

validator.showErrors({"firstNameCtrl": "", "lastNameCtrl": "", "companyNameCtrl": "", });
0
 

Author Comment

by:obb-taurus
ID: 37773739
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37774187
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
 

Author Comment

by:obb-taurus
ID: 37774944
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37775907
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
 

Accepted Solution

by:
obb-taurus earned 0 total points
ID: 37779239
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37779651
i think you're right on. just try!
0
 

Author Closing Comment

by:obb-taurus
ID: 37795234
Thanks for all your help
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now