简体   繁体   English

带有JQuery表单验证器Rails Gem的表单字段的条件验证

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

I'm working on a group rails app that uses the jquery-form-validator-rails gem for form field validation. 我正在使用使用jquery-form-validator-rails gem进行表单字段验证的Group Rails应用程序。 I can perform simple validation using the data object on the field, like so: 我可以使用字段上的数据对象执行简单的验证,如下所示:

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

However, I cannot figure out how to add conditional validation rules. 但是,我不知道如何添加条件验证规则。 I need a specific field to be required only when another field contains a certain value (ex: #other_component_id is required only when the select field, #component_id, includes 'other' as a value). 我仅在另一个字段包含某个值时才需要一个特定字段(例如:仅在选择字段#component_id包含“ other”作为值时,才需要#other_component_id)。

I've tried adding rules within the $.validate() call but they do not seem to apply. 我试过在$ .validate()调用中添加规则,但是它们似乎并不适用。

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

Applying the validate() method to the specific form does not work either. 将validate()方法应用于特定形式也不起作用。

Because this app is shared, I have to use the jquery-form-validator-rails gem for form validation. 因为此应用程序是共享的,所以我必须使用jquery-form-validator-rails gem进行表单验证。

Never mind. 没关系。 It turns out I was using the incorrect format for applying the validation (although the 'required' validation was working, max length was not). 事实证明,我使用了不正确的格式来应用验证(尽管“必需”验证有效,但最大长度却无效)。 I changed that to instead use this format: 我将其更改为改为使用以下格式:

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

I was then able to add a custom validator and apply that to my field. 然后,我可以添加一个自定义验证器并将其应用于我的字段。

JS: 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'
});

If anyone has suggestions for a more efficient method of conditional validation, I'd be interested to hear them. 如果有人对采用更有效的条件验证方法有任何建议,我很想听听他们的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM