簡體   English   中英

帶有JQuery表單驗證器Rails Gem的表單字段的條件驗證

[英]Conditional Validation of Form Fields w/ JQuery Form Validator Rails Gem

我正在使用使用jquery-form-validator-rails gem進行表單字段驗證的Group Rails應用程序。 我可以使用字段上的數據對象執行簡單的驗證,如下所示:

<%= f.text_field(:name , class: "form-control", data: { :validation => "required validate_max_length length255", "validation-error-msg" => "Required Field, 255 characters max"}) %>

但是,我不知道如何添加條件驗證規則。 我僅在另一個字段包含某個值時才需要一個特定字段(例如:僅在選擇字段#component_id包含“ other”作為值時,才需要#other_component_id)。

我試過在$ .validate()調用中添加規則,但是它們似乎並不適用。

$().validate({
      rules: {
        other_component_id: {
          required: function(element) {
            return $('#component_id').val().includes('other');
          }
        }
      }
    });

將validate()方法應用於特定形式也不起作用。

因為此應用程序是共享的,所以我必須使用jquery-form-validator-rails gem進行表單驗證。

沒關系。 事實證明,我使用了不正確的格式來應用驗證(盡管“必需”驗證有效,但最大長度卻無效)。 我將其更改為改為使用以下格式:

<%= f.text_field(:name , class: "form-control", data: { :validation => 'length', 'validation-length' => '1-255',
                                                                                'validation-error-msg' => 'Required Field, 255 characters max'}) %>

然后,我可以添加一個自定義驗證器並將其應用於我的字段。

JS:

$.formUtils.addValidator({
  name : 'comp_required',
  validatorFunction : function(value, $el, config, language, $form) {
    if ($('#component_id').val().includes('other')) {
      if (value.length > 0 && value.length <= 32) {
        return true;
      }
    } else {
      return true;
    }
  },
  errorMessage : 'You must enter a new component name. Max length = 32',
  errorMessageKey: 'badComponentName'
});

如果有人對采用更有效的條件驗證方法有任何建議,我很想聽聽他們的建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM