LoginSignup
3
3

More than 5 years have passed since last update.

select2でjQuery Validation Engineを使う方法

Last updated at Posted at 2016-05-20

Select2の4.0.2から、特別にオプションを設定しなくてもjQuery Validation Engineを併せて使えるようになった。
selectタグをdisplay:noneするのではなく、最小化して見えなくする方式に変わったため。


Validation Engine 2.6.2
Select2 4.0.0-rc.2

select2はselectをフィルタ付きのselectにしてくれるプラグイン。
jQuery Validation Engineはformの各タグにバリデーションを行うことができるプラグイン。

select2でjQuery Validation Engineを使う方法。

1.html

<select class="validate[required]" data-promptPosition="inline">
  <option>鎌倉
  <option>横浜
</select>

2.オプションを設定

$('form').validationEngine({
    validateNonVisibleFields: true,
    promptPosition:'inline'
});

※promptPositionのinlineはhmtlのdata1属性またはjsのオプションで設定する。

解説

1.validateNonVisibleFields: true

select2はselectタグをdisplay:noneで非表示にして、spanタグでフィルタリン付きのselectを表示している。spanタグのフィルタリン付きのselectを変更すると、selectタグに反映される。
validationEngineはデフォルトでは、非表示タグは対象外(false)なのでオプションで対象(true)に変更する。

2.promptPosition:'inline'

デフォルトのバリデーションメッセージは右上に表示されるが、これはバリデーション対象のタグの位置を計測して表示している。
位置の計測はposition().topを使っているため、display:noneでは正確に計測できない。そのため計測の必要がないinlineを使用している。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3