2

I'm having trouble attaching a call back to jquery unobtrusive validate. What I want to do is hide an informational message any time a field validation error is shown. They both take up the same area on the page. I can't figure out how to attach a callback to the show error method. I have one that works if you call validate but the error messages are shown before even change for the field is fired.

Here is a jsfiddle demoing my problem. http://jsfiddle.net/K6NcF/4/

This is the callback that only runs when validate() is called.

$('#theForm').bind('invalid-form.validate',function(){
    $('.info-box').hide();
});

Any help would be appreciated.

  • I'm not 100% sure how to do this with `unobtrusive`, but just with jQuery Validate plugin, there are a whole bunch of callback functions you can play with. See docs: http://docs.jquery.com/Plugins/Validation/validate#toptions – Sparky Apr 24 '13 at 16:19
  • Another issue I see in your jsFiddle; `
    ` - it may or may not be valid HTML to have an `id` start with a number, but it's definitely not a good practice. See: http://stackoverflow.com/a/79022/594235
    – Sparky Apr 24 '13 at 16:20
  • Yeah the problem is I don't believe I can use any of those call backs because they don't cause the validation messages to show while the user is editing the field. It tried binding a call back to show errors with no success. Good call on the id, though that's not the problem, I don't know why my go to was 1 but I updated it. – Robert Garrett Apr 24 '13 at 17:46
  • `highlight` and `unhighlight` are fired in sync with validation of each field. e.g., if you left the `onkeyup` option default in place, then a `highlight` or `unhighlight` callback will fire on every keystroke. (By default, these update the `valid/error` classes on the element. [See source code for default functions](http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js).) – Sparky Apr 24 '13 at 21:10

1 Answers1

1

You can access the highlight and unhighlight callbacks when using unobtrusive like this

// grab a reference to the validator instance
var v = $('form').validate();

// reference the settings property, and the highlight function
var originalHighlight = v.settings.highlight;

You could just overwrite this with your stuff, or the example below shows a way to add your own functionality without overwriting what is there.

var v = $('#theForm').validate();

var originalHighlight = v.settings.highlight;
var originalUnHighlight = v.settings.unhighlight;

v.settings.highlight = function(element, errorClass, validClass)
{
  console.log('doing my stuff here');
  $('.info-box').hide();
  originalHighlight.call(v, element, errorClass, validClass);
}

v.settings.unhighlight = function(element, errorClass, validClass)
{
  console.log('undoing my stuff here');
  $('.info-box').show();
  originalUnHighlight.call(v, element, errorClass, validClass);
}

fiddle here http://jsfiddle.net/K6NcF/8/

politus
  • 5,996
  • 1
  • 33
  • 42