Mike Lucid
Mike Lucid

Reputation: 1354

custom method to check if child div hasClass - jquery validate

I have been fighting with a custom validation all day, I thought it was about time to ask for some help.

What I have built is a select user interface similar to facebook when you add users to an event. I am trying to build a function that will return an error if none of the users are selected. The problem I am running into is that the parent div needs to be treated like a form element, but I can find any info on how to do that.

Another thought came to me while i was making the JSfiddle. I store the User ID's in an array. Maybe the validation could check for an empty array? Im not sure how to do that either, or which way would be ideal..

Here is a fiddle to play with: http://jsfiddle.net/7neCU/1/

Here is what I have tried so far.

    $.validator.addMethod('require-one-div', function (element) {
        if ($('#trainees').children('.each_user').hasClass('selected'))
            return true;
        }, "Please select at least 1 trainee");

and the rules

    rules: {
            trainees:{
                'require-one-div':true
            },
        }

I also gave the parent div #trainees the name & id "trainees" and class of required.

Thank you for any suggestions or ideas.

Upvotes: 1

Views: 1777

Answers (2)

Ryley
Ryley

Reputation: 21226

jQuery Validate does not support rules on a section. It is a form plugin. So you must be using input,textarea,select.

As was suggested in a comment, you probably need a few things:

  1. Make a hidden checkbox group or radio group
  2. Hook clicks of your profiles into each checkbox or radio
  3. Call validate on that, but make sure to specify ignore: '', otherwise validate will ignore any hidden form fields.

Upvotes: 1

neouser99
neouser99

Reputation: 1827

Humm.... not 100% sure how this validation plugin works. But a method could simple do this as the "validation" step.

$.validator.addMethod('require-one-div', function (element) {
    return $('#trainees .each_user.selected').length;
}, "Please select at least 1 trainee");

Basically it says, if there are 0 .selected .each_user divs, the validation will return 0 (falsy). If there is at least one, .length >= 1 is truthy, meaning validation passes. If the validation is the opposite, just tack a ! in front of the length check !$('#trainees .each_user.selected').length

Upvotes: 0

Related Questions