Custom validator method not working
I'm trying to add a few custom methods to the validator. It doesn't seem to be working properly.
I have an activity drop down. An activity has to be selected. If the value of the activity is 1, 2, or 3 a division and account have to be selected as well. Otherwise those fields can be empty.
I've tried to alert the values in my custom methods but it doesn't seem to fire all the time and even when the value is greater than 3 it doesn't clear the errors if they show up. I guess I'm thinking the validator fires on the value change in each of the fields of the form, but maybe it only fires on the submit function.
Here is the javascript I'm using:
- jQuery.validator.addMethod('activitySelected', function (value, element) {
- value = parseInt(value.replace(/\s+/g, ''));
- return this.optional(element) || value > 0;
- }, 'Please select an activity.');
-
- jQuery.validator.addMethod('accountSelected', function (value, element) {
- value = parseInt(value.replace(/\s+/g, ''));
- var activity = parseInt($('#activity').val());
- alert(activity);alert(this.optional(element));alert(((activity > 0 || activity < 4) && value > 0));
- return this.optional(element) || ;
- }, 'Please select an account.');
-
- jQuery.validator.addMethod('divisionSelected', function (value, element) {
- value = parseInt(value.replace(/\s+/g, ''));
- var activity = parseInt($('#activity').val());
- return this.optional(element) || ((activity > 0 || activity < 4) && value > 0);
- }, 'Please select a division.');
- $('#log_form').validate({
- rules: {
- time_start: {
- required: true
- },
- time_end: {
- required: true
- },
- activity: {
- activitySelected: true
- },
- account: {
- accountSelected: true
- },
- division: {
- divisionSelected: true
- }
- },
- highlight: function(el) {
- $(el).closest('.control-group').removeClass('success').addClass('error');
- },
- success: function(el) {
- $(el).closest('.control-group').removeClass('error');
- },
- submitHandler: function(form) {
- form.submit();
- }
- });