?
Solved

Jquery validation - greater than validation code

Posted on 2009-12-29
8
Medium Priority
?
6,733 Views
Last Modified: 2012-06-21
Hello,

I'm using jquery validate plugin. It doesnt have code to test for greater than/ lesser than values included. I need to make sure that the value of the select box is always lower than the other checkbox.

I found this custom code but its not working:

// custom code for greater than
jQuery.validator.addMethod('greaterThan', function(value, element, param) {
return ( value > jQuery(param).val() );
}, 'Must be greater than start' );

// custom code for lesser than
jQuery.validator.addMethod('lesserThan', function(value, element, param) {
return ( value < jQuery(param).val() );
}, 'Must be less than end' );


Then, amongst my validation routine I have:

aupairShortStay: {required:true, lesserThan: "#aupairLongStay"},
aupairLongStay: {required:true, greaterThan: "#aupairShortStay"}


And the html for the select boxes

<div class="fieldsHolder">
 <div class="field_left">
  <label class="req" for="aupairShortStay">Shortest term of stay<span>*</span></label>
  <select name="aupairShortStay" class="error">
        <option value="">Select One</option>
   
        <option value="1">1 month</option>
   
        <option selected="" value="2">2 months</option>
   
        <option value="3">3 months</option>
   
        <option value="4">4 months</option>
   
        <option value="5">5 months</option>
   
        <option value="6">6 months</option>
   
        <option value="7">7 months</option>
   
        <option value="8">8 months</option>
   
        <option value="9">9 months</option>
   
        <option value="10">10 months</option>
   
        <option value="11">11 months</option>
   
        <option value="12">12 months</option>
   
        <option value="13">13 months</option>
   
        <option value="14">14 months</option>
   
        <option value="15">15 months</option>
   
        <option value="16">16 months</option>
   
        <option value="17">17 months</option>
   
        <option value="18">18 months</option>
   
        <option value="19">19 months</option>
   
        <option value="20">20 months</option>
   
        <option value="21">21 months</option>
   
        <option value="22">22 months</option>
   
        <option value="23">23 months</option>
   
        <option value="24">24 months</option>
   
  </select><label for="aupairShortStay" generated="true" class="error">Must be less than end</label>
 </div>
 <div class="field_right">
 <label class="req" for="aupairLongStay">Longest term of stay<span>*</span></label>
 <select name="aupairLongStay" class="">
       <option value="">Select One</option>
 
       <option value="1">1 month</option>
 
       <option value="2">2 months</option>
 
       <option selected="" value="3">3 months</option>
 
       <option value="4">4 months</option>
 
       <option value="5">5 months</option>
 
       <option value="6">6 months</option>
 
       <option value="7">7 months</option>
 
       <option value="8">8 months</option>
 
       <option value="9">9 months</option>
 
       <option value="10">10 months</option>
 
       <option value="11">11 months</option>
 
       <option value="12">12 months</option>
 
       <option value="13">13 months</option>
 
       <option value="14">14 months</option>
 
       <option value="15">15 months</option>
 
       <option value="16">16 months</option>
 
       <option value="17">17 months</option>
 
       <option value="18">18 months</option>
 
       <option value="19">19 months</option>
 
       <option value="20">20 months</option>
 
       <option value="21">21 months</option>
 
       <option value="22">22 months</option>
 
       <option value="23">23 months</option>
 
       <option value="24">24 months</option>
 
 </select>
 </div>
</div>


Thanks for any help
0
Comment
Question by:Mark Steggles
  • 5
  • 3
8 Comments
 
LVL 61

Expert Comment

by:HainKurt
ID: 26143523
can you please post the code for your "validation routine" ;)
0
 
LVL 30

Author Comment

by:Mark Steggles
ID: 26143576
attached
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z ]+$/i.test(value);
});

// custom code to for greater than
jQuery.validator.addMethod('greaterThan', function(value, element, param) {
return ( value > jQuery(param).val() );
}, 'Must be greater than start' );

// custom code for lesser than
jQuery.validator.addMethod('lesserThan', function(value, element, param) {
return ( value < jQuery(param).val() );
}, 'Must be less than end' );



$(function(){
$("#form_reg").validate({

rules: {
   firstName: {
	required: true,
	minlength: 2,
	lettersonly: true
   },
   lastName: {
	required: true,
	minlength: 2,
	lettersonly: true
   },
   emailAddress: {
      required: true,
      email: true
   },
   emailConfirm: {
      required: true,
      email: true,
      equalTo: "#emailAddress"
   },
   accessLevelID: "required",
  /* countryID: "required", */
   zipCode: {
      required: true,
      number: true,
      minlength: 5,
      maxlength: 5
   },
   aupairAgeRange: "required",
   aupairBefore: "required",
   aupairCar: "required",
   aupairCouple: "required",
   aupairCPR: "required",
   aupairDearFamily: {maxlength: 5000},
   aupairDietNeeds: "required",
   aupairDriver: "required",
   aupairEducation: "required",
   aupairEndDate: "required",
   aupairFamilyAge: "required",
   aupairFirstAid: "required",
   aupairGender: "required",
   aupairHealth: "required",
   aupairHeight: "required",
   aupairHours: "required",
   aupairJobDesc: {maxlength: 5000},
   aupairLanguageList: "required",
   aupairLiveIn: "required",
   aupairLongStay: {required:true, greaterThan: "#aupairShortStay"},
   aupairMarried: "required",
   aupairRefs: "required",
   aupairShortStay: {required:true, lesserThan: "#aupairLongStay"},
   aupairSingleFamily: "required",
   aupairSmoker: "required",
   aupairStartDate: "required",
   aupairswim: "required",
   aupairSwimmer: "required",
   aupairWeight: "required",
   canOwnCar: "required",
   ccExpMonth: "required",
   ccNum: {	required: function(element) {
						if ($(".ccType:checked").val() != "Paypal" && $(".ccType:checked").val() != "Western Union") return true; else return false;
					} ,
					creditcard: true},
   ccnumber: {required:true, creditcard: true},
   childAgeList: "required",
   cityselect: "required",
   countryList: "required",
   cvv2: {digits: true, required: function(element) {
						if ($(".ccType:checked").val() != "Paypal" && $(".ccType:checked").val() != "Western Union") return true; else return false;
					} 
				},
   expMonth: "required",
   expYear: "required",
   familyAgeGroup: "required",
   familyDearAupair: {maxlength: 5000},
   familyRefs: "required",
   featureID: "required",
   fulltime: "required",
   headline: {required: true, maxlength: 54},
   languageList: "required",
   limitToPrefCities: "required",
   nationalityID: "required",
   nationalityIDPref: "required",
   numChildren: "required",
   passportCountryID: "required",
   phoneNumber: "required",
   phoneNumber1: "required",
   postalAddress1: "required",
   pref_currency_code: "required",
   prefCity: "required",
   prefNationalityID: "required",
   read_tos: "required",
   religionID: "required",
   salaryExpectation: "required",
   seccode: {required:true, maxlength:3, number: true},
   securityAnswer: "required",
   securityQuestion: "required",
   singleParent: "required",
   ssn: {maxlength: 4, number: true},
   state: "required",
   visaIDs: "required"
},
messages: {
	firstName: {
		required: "First Name is required.",
		minlength: "Must be at least two characters.",
		lettersonly: "Letters only please."
	},
	lastName: {
		required: "Last Name/Surname is required.",
		minlength: "Must be at least two characters.",
		lettersonly: "Letters only please."
	},
	emailAddress: {
		email: "Please enter a valid email address."
	},
	emailConfirm: {
		equalTo: "Please fix your email addresses so they match."
	},
	aupairLanguageList: "Select all required languages.",
	languageList: "Select one or more languages.",
	prefNationalityID: "Select your preferred Nationalities.",
	aupairEndDate: {
		greaterThan: "Must be later than start date."
	}
},
errorPlacement: function(error, element) {
     if (element.attr("name") == "read_tos")
       error.insertAfter(".read_confirm");
       else if (element.attr("name") == "aupairLanguageList") 
          error.insertAfter("#multiSelect-aupairLanguageList-content");
	else if (element.attr("name") == "languageList")
          error.insertAfter("#multiSelect-languageList-content");
	else if (element.attr("name") == "prefNationalityID")
          error.insertAfter("#multiSelect-prefNationalityID-content");
       else if ($(element).is("input[type='radio']"))
          error.insertAfter($(element).parents('div:first'));
     else
       error.insertAfter(element);
   },
 
highlight: function(element, errorClass) {
     if ($(element).attr("name") == "aupairLanguageList") 
        $("#multiSelect-aupairLanguageList-title").addClass("error");
	else $(element).addClass(errorClass);
  },
  unhighlight: function(element, errorClass) {
     if ($(element).attr("name") == "aupairLanguageList") 
        $("#multiSelect-aupairLanguageList-title").removeClass("error");
	else $(element).removeClass(errorClass);
  }
  
});

$("input#checkoutButton").click(function() {
	if ($("#form_reg").valid()) {
		$("input#checkoutButton").hide();
	}
});

});

/* the function to show the tips based on the class .tip */
$(document).ready(function(){
            $(".tip").focus(function () {
                var id  = this.id;
                id     += 'Tip';
            
                $("#" + id).css('display','block');
            });
            $(".tip").blur(function () {
                var id  = this.id;
                id     += 'Tip';
            
                $("#" + id).css('display','none');
            });
	/* tip function end */
	
	    $(".emailTip").focus(function () {
	    	$("#emailTip").css('display','block');
            });
	    $(".emailTip").blur(function () {
	    	$("#emailTip").css('display','none');
            });
	    
	     $(".accessJobSeeker").focus(function () {
	    	$("#accessJobSeekerTip").css('display','block');
        });
	    $(".accessJobSeeker").blur(function () {
	    	$("#accessJobSeekerTip").css('display','none');
        });
		$(".accessFamily").focus(function () {
	    	$("#accessFamilyTip").css('display','block');
        });
	    $(".accessFamily").blur(function () {
	    	$("#accessFamilyTip").css('display','none');
        });
        $("#countryID").mouseover(function () {
	    	$("#countryIDTip").css('display','block');
            });
	    $("#countryID").mouseout(function () {
	    	$("#countryIDTip").css('display','none');
            });
	    $("#weWantToHireCheck").mouseover(function () {
	    	$("#weWantToHireCheckTip").css('display','block');
            });
	    $("#weWantToHireCheck").mouseout(function () {
	    	$("#weWantToHireCheckTip").css('display','none');
            });
	    $("#ourJobRequiresCheck").mouseover(function () {
	    	$("#ourJobRequiresCheckTip").css('display','block');
            });
	    $("#ourJobRequiresCheck").mouseout(function () {
	    	$("#ourJobRequiresCheckTip").css('display','none');
            });
	    $("#areYouSingleParent").mouseover(function () {
	    	$("#areYouSingleParentTip").css('display','block');
            });
	    $("#areYouSingleParent").mouseout(function () {
	    	$("#areYouSingleParentTip").css('display','none');
            });
	     $("#aupairCouple").mouseover(function () {
	    	$("#aupairCoupleTip").css('display','block');
            });
	    $("#aupairCouple").mouseout(function () {
	    	$("#aupairCoupleTip").css('display','none');
            });
        $("#countrydiv").mouseover(function () {
	    	$("#prefCitiesTip").css('display','block');
            });
	    $("#countrydiv").mouseout(function () {
	    	$("#prefCitiesTip").css('display','none');
            });
	    $("#limitJobsToCities label").mouseover(function () {
	    	$("#limitJobsToCitiesTip").css('display','block');
            });
	    $("#limitJobsToCities label").mouseout(function () {
	    	$("#limitJobsToCitiesTip").css('display','none');
            });
	    $("#bDay,#bMonth,#bYear").focus(function () {
	    	$("#DOBTip").css('display','block');
            });
        $("#bDay,#bMonth,#bYear").blur(function () {
	    	$("#DOBTip").css('display','none');
        });
        
});

/* textarea remaining characters script from http://pure-essence.net/stuff/webTips/dodosTextCounter/index.html */
jQuery.fn.dodosTextCounter=function(a,b){b=$.extend({counterDisplayElement:"span",counterDisplayClass:"dodosTextCounterDisplay",addLineBreak:true},b);$(this).each(function(i){updateCounter(this,a,b,i);$(this).keyup(function(){updateCounter(this,a,b,i);return this})});return this};function updateCounter(a,b,c,d){var e=0;var f=$(a).val();if(f){e=f.length}if(e>b){$(a).val(f.substring(0,b))}else{var g=b-e;var h=c.counterDisplayElement+"."+c.counterDisplayClass+":eq("+d+")";var i=$(h).length==0;if(i){var j=document.createElement(c.counterDisplayElement);if(c.counterDisplayElement=='input'){$(j).val(g.toString())}else{$(j).html(g.toString())}$(j).addClass(c.counterDisplayClass).insertAfter($(a));if(c.addLineBreak){$(a).after("<br />")}}else{if(c.counterDisplayElement=='input'){$(h).val(g.toString())}else{$(h).html(g.toString())}}}}

$(document).ready(function(){
	$(".remainingHeadline").dodosTextCounter(54, {counterDisplayClass: "remainingHeadChar",addLineBreak:false});
	$(".remainingTextarea").dodosTextCounter(5000, {counterDisplayClass: "remainingChar",addLineBreak:false});
});

Open in new window

0
 
LVL 61

Expert Comment

by:HainKurt
ID: 26143610
I guess this is working ;) learning jQuery...
    <script type="text/javascript">

// custom code for greater than
jQuery.validator.addMethod('greaterThan', function(value, element, param) {
	//alert(value + " - " + element.value + " - " + param[0]);
return ( value > jQuery(param).val() );
}, 'Must be greater than start' );

// custom code for lesser than
jQuery.validator.addMethod('lesserThan', function(value, element, param) {
	//alert(value + " - " + element.value + " - " + param[0]);
return ( value < jQuery(param).val() );
}, 'Must be less than end' );

$(document).ready(function(){
$('#frmTest').validate({ 
    rules : { 
			aupairShortStay: {required:true, lesserThan: $("#aupairLongStay")},
			aupairLongStay: {required:true, greaterThan: $("#aupairShortStay")}
    } 
	}); 

});
    </script>

Open in new window

0
Industry Leaders: 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!

 
LVL 61

Accepted Solution

by:
HainKurt earned 2000 total points
ID: 26143619
only change is this:

aupairShortStay: {required:true, lesserThan: "#aupairLongStay"},
aupairLongStay: {required:true, greaterThan: "#aupairShortStay"}
-->
aupairShortStay: {required:true, lesserThan: $("#aupairLongStay")},
aupairLongStay: {required:true, greaterThan: $("#aupairShortStay")}

also, we may change to

jQuery.validator.addMethod('greaterThan', function(value, element, param) {
  return ( value > jQuery(param[0]).val() );
}, 'Must be greater than start' );

but I guess you pass one parameter, so it should be ok...
0
 
LVL 30

Author Comment

by:Mark Steggles
ID: 26146967
I just updated these two lines:

aupairShortStay: {required:true, lesserThan: $("#aupairLongStay")},
aupairLongStay: {required:true, greaterThan: $("#aupairShortStay")}

Do I need to do anything else? that didn't fix the problem



Thanks for your help so far.
0
 
LVL 61

Expert Comment

by:HainKurt
ID: 26148714
check my post, maybe you are missing something...
check the id of the elements & form
0
 
LVL 61

Assisted Solution

by:HainKurt
HainKurt earned 2000 total points
ID: 26148723
if you have $("#someElm") then you should have an element with id="someElm"
0
 
LVL 30

Author Comment

by:Mark Steggles
ID: 26148981
duh :) I didnt have the id's on the select boxes
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What is a Lightbox? A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions. There are lots of Lightbox effects for jQuery. Problem is they are a…
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
The viewer will learn how to dynamically set the form action using jQuery.
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)
Suggested Courses
Course of the Month15 days, 17 hours left to enroll

850 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