Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate: How to validate a non-form element?

I have a form that has an attached map. Clicking on the map adds hidden inputs to a div in the form.

I want a validation rule to check whether or not that div has any hidden elements. So far, I've only been able to do this with a dummy element that I have to manually remove before posting the form:

<form action="..." method="post" id="signup">
  <!-- ... -->
  <div id="zones_selected"><input type="hidden" name="dummy"></div>
  <!-- ... -->
</form>

$.validator.methods.zones = function (value, element, param) { return ($zone_holder.find('input[name!=dummy]').length > 0); };
$('#signup').validate({
  rules: {
    //...
    'dummy': 'zones'
  },
  //...
  submitHandler: function(form) { $(form).find('input[name=dummy]').remove(); form.submit(); }
});

However, these leaves much to be desired for error placement, as my custom validator method doesn't seem to ever trigger the unhighlight function, and I feel dirty for having put in an input solely for form validation (not very unobtrusive).

What I would like is no extra submitHandler and a rule to check the presence of hidden inputs in a div that would have an unhighlight trigger (such that if a user does click on the map--which creates a new hidden input--the message I display telling them to do so will disappear).

What's the best way to accomplish this?

like image 543
neezer Avatar asked Sep 17 '10 13:09

neezer


1 Answers

I've tried to do this in the past. I don't believe there is a way to do it without doing some modifications to the jquery.validator code base.

When looking at JQuery.Validator.js, check out 'elements' function on ln 423 you'll see something like this

return $([]).add(this.currentForm.elements)
            .filter(":input")
            .not(":submit, :reset, :image, [disabled]")
            .not( this.settings.ignore )
            .filter(function() {
                !this.name && validator.settings.debug && window.console && console.error( "%o has no name assigned", this);

                // select only the first element for each name, and only those with rules specified
                if ( this.name in rulesCache || !validator.objectLength($(this).rules()) )
                    return false;

                rulesCache[this.name] = true;
                return true;
            });

The filter(":input") is what will give you grief.

like image 126
Chris Brandsma Avatar answered Oct 22 '22 22:10

Chris Brandsma