@ledsun blog

無味の味は佳境に入らざればすなわち知れず

jQuery.validateはform専用だった。

form専用なの?

An error is encountered in below case.
I use jQuery.validate wtih jQuery.ui.dialog.

  1. At first, I validate to div in form.
  2. I show dialog, the div move out of the form*1, and a focusin event triggered to the first input element*2.
  3. So, delegate function is called, but $.data(this[0].form, "validator") is null, because the div is out of the form.
  4. An error is encountered.
$('form #div1').validate();
$('form #div1').dialog();

This is incorrect use of validate function?
validate function is only for form element?

ソースを見ると

In 'validate' function, validator is stored in $.data(this[0], 'validator').

validator = new $.validator( options, this[0] );
$.data(this[0], 'validator', validator);

In 'delegate' function, validator is getted from $.data(this[0].form, "validator").

function delegate(event) {
    var validator = $.data(this[0].form, "validator"),
        eventType = "on" + event.type.replace(/^validate/, "");
    validator.settings[eventType] && validator.settings[eventType].call(validator, this[0], event);
}

APIドキュメント見たら

.validate() | jQuery Validation Plugin

Validates the selected form.

だってさ。
ちっきしょ、このバグ解析すんのに2日掛かった。良い子のみんなは、英語のAPIドキュメントもちゃんと読もうね。

*1:jQuery.ui.dialogはどういうわけかダイアログ表示したdivを一番下(formの外)に移動する。

*2:一つ目の要素がチェックボックスだとfocusinイベントが飛んでこないから、このエラーは起きないんだ。これで混乱した。