1

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.

2
  • A validation plugin is likely to look for input fields. Why not add input type='hidden' with true/false values set with a click event? Commented Dec 14, 2012 at 0:47
  • I am currently trying this, thanks fo the suggestion Commented Dec 14, 2012 at 16:43

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

hey thanks alot! I seemed to have gotten it to work with this info.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.