Rails 3 UJS 干客户端 +服务器端表单验证
使用 jQuery 进行表单验证就像向字段添加类名一样简单。使用 Rails 进行表单验证就像将条件放入控制器(和/或模型)中一样简单。
我认为应该有一种方法可以编写一次验证并将它们应用到客户端和服务器端。我一直热衷于编写自己的 javascript,但凭借 Rails3 的不引人注目性,如果 UJS 能够实现这一目标,那么它在这里可能非常值得。
谢谢!!
Form validation with jQuery is as easy as adding a classname to a field. Form validation with rails is as easy as putting a condition in to your controller (and/or model).
I figure there should be a way to write the validations once and have them applied both client and server side. I've always been a fan of writing my own javascript, but with rails3 unobtrusivity UJS might be well worthwhile here if it can accomplish this.
Thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该考虑创建自己的表单构建器来自定义
form_for
的行为。您可以执行一些操作,将类设置为属性上定义的验证名称,并将 jQuery 将自身绑定到相应的类名称。让我们从表单生成器的外观开始。您需要设置
form_for
才能使用 ValidationFormBuilder。如果您需要对类名称有更大的灵活性,您可能需要创建一个映射到所需字符串的散列。
您可以通过查看 Rails 源代码的
activemodel/lib/active_model/validations
来查看 Rails 中包含的验证的完整列表。我希望这足以让您开始。You should look at creating your own form builder for customising the behaviour of
form_for
. You could do something that sets the class to the name of the validations defined on the attribute and have jQuery bind itself to the respective class names. Let's start with what the form builder might look like.You'll need to setup
form_for
to use the ValidationFormBuilder.If you need more flexibility over the class names, you might want to create a hash that maps to the desired string.
You can see the complete list of validations included in Rails by peeking in
activemodel/lib/active_model/validations
of the Rails source code. I hope that's enough to get you started.https://github.com/alluniq/validated-fields
https://github.com/alluniq/validated-fields
您可以使用 RJS 进行服务器端验证(并且它不取决于您是否使用 UJS):
You can use server side validation using RJS (and it doesn't depend on you are using UJS or not):
是否有 JS 验证,包括一些简洁的 ajax 来验证唯一性。
https://github.com/bcardarella/client_side_validations
http://railscasts.com/episodes/263-client-side-validations
Does JS validations, including some neat stuff ajax for validating uniqueness.
https://github.com/bcardarella/client_side_validations
http://railscasts.com/episodes/263-client-side-validations