动态嵌套模型字段上的 Rails JavaScript 验证

发布于 2024-10-12 06:21:38 字数 486 浏览 3 评论 0原文

我有一个嵌套模型表单,用户可以在其中创建一个“项目”,其中可以包含任意数量的“任务”,其中包含任务“名称”和“描述”。这些任务由用户使用 jQuery 动态添加。

我想为每个任务中的字段提供客户端验证,目前我正在使用 livevalidation 插件。

问题是输入字段根据当前时间被赋予一个动态 id,因为它们必须是唯一的,以便 Rails 在提交表单时执行其操作。

在我看来,我有两个选择:

  1. 以某种方式让 javascript 验证接受通配符,以便每次添加任务时,都可以根据其 id 中未更改的部分对其字段设置验证.

  2. 在创建任务的同时创建必要的内联验证 javascript。

上面的方法有用吗?还有更好的选择吗?如何将从部分 id 匹配中选择的元素放入验证器中?

谢谢

I have a nested model form where the user can create a "project" that can include any number of "tasks" which consist of a taks "name" and "description". These tasks get added dynamically by the user using jQuery.

I want to provide client side validations for the fields in each of these tasks, currently I am using the livevalidation plugin.

The problem is that the input fields are given a dynamic id based on the current time since thay have to be unique for Rails to do its stuff when the form is submitted.

The way I see it, I have two options:

  1. Somehow get the javascript validations to accept a wildcard so that every time a task is added, validations can be set against its fields based on the part of its id that does not change.

  2. Create the necessary validation javascript inline at the same time that the task is created.

Would the above work? are there any better options? how would I get an element selected from a partial id match into the validator?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤檠 2024-10-19 06:21:38

我建议使用 jQuery 验证插件。它允许您根据属性名称而不是 ID 创建验证,并且您可以对不同的表单使用相同的规则集:

validation = { rules: { "name": "required", "description": "required" } }
jQuery("#form-1").validate(validation);
jQuery("#form-2").validate(validation);

如果您想传递显式 ID,您可以使用函数来生成规则:

function validation_rules(index){
  return {
    rules: {
      "name["+index+"]": "required",
      "description["+index+"]": "required"
    }
  };
}

I would recommend using the jQuery Validation Plugin. It lets you create validations based on the attribute names instead of their IDs, and you can use the same set of rules for different forms:

validation = { rules: { "name": "required", "description": "required" } }
jQuery("#form-1").validate(validation);
jQuery("#form-2").validate(validation);

If you want to pass explicit ids you can use a function to generate your rules:

function validation_rules(index){
  return {
    rules: {
      "name["+index+"]": "required",
      "description["+index+"]": "required"
    }
  };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文