如何重构重复的 jquery 验证方法?

How can I refactor duplicate jquery validation methods?

在我的 rails 应用程序中,我在页面加载时加载的 js.erb 文件中有此 jquery 验证代码。

  if ($('#custom-tag').length) {
    $('#custom-tag').validate({
      onfocusout: false,
      rules: {
        tag: {
          minLengthSquish: 2,
          maxLengthSquish: 25
        }
      },
      tooltip_options: {
        tag: { placement: 'right', animation: false }
      }
    });
  }

表单在页面加载时存在,但用户可以通过 ajax 请求添加和删除标签。对于每个请求,表单都会重新呈现,因为表单只会在标签计数为 5 或更少时显示,因此我需要在每次加载表单时重新初始化 jquery 验证。我的 add_tag.js.erb 和 remove_tag.js.erb 文件中存在完全相同的代码,这些文件是通过 ajax.

从控制器调用的

我只是想知道在三个地方使用这个重复代码是否是实现此目的的唯一方法。

The form is there on page load but the user is able to add and remove tags through ajax request. With each request the form is re-rendered because the form will only display if the tag count is 5 or less, so I need to reinitialize jquery validate each time the form loads.

不能 "reinitialize" jQuery 在同一表单上验证。对 .validate() 的后续调用总是被忽略。

每当您更改表单时,您都可以 use the .rules() method 动态地 addremove 规则。

// on page load
$('#custom-tag').validate({ // initialize plugin on the form; can only be done once
    // options, etc.
    onfocusout: false,
    rules: {   // initial rules
        tag: {
            minLengthSquish: 2,
            maxLengthSquish: 25
        }
    }
});

// make changes dynamically
$('.newfields').each(function() { // add rules to multiple fields
    $(this).rules('add', {
        minLengthSquish: 5,
        maxLengthSquish: 50
    });
});

$('[name="tag"]').rules('add', {  // add rules to one field
    minLengthSquish: 30,
    maxLengthSquish: 55
});

$('[name="tag"]').rules('remove');  // remove all rules from one field