如何在Grails中的单个域类上使用多个约束? [英] How can I use more than one set of constraints on a single domain class in Grails?

查看:89
本文介绍了如何在Grails中的单个域类上使用多个约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在保存时间选择一组验证规则.理想情况下,我希望能够在域类中定义一组以上的约束:

I need to choose a set of validation rules at save time. Ideally I would like to be able to define more than one set of constraints in the domain class:

class Account {
    ...
    static constraints = { ... }
    static constraints2 = { ... }
}    

我知道我可以在代码中进行自己的验证(account.errors.rejectValue(...)等),但我希望通过使用内置的Grails验证来节省一些时间.

I know I can do my own validation in code (account.errors.rejectValue(...) etc) but I am looking to save some time by using the built in Grails validation if possible.

推荐答案

这是您不能只换掉验证的原因是,验证还有助于定义数据库结构,例如将字段设置为非空,非空白或具有特定长度.例如,关闭"non-null"可能会破坏数据库结构.

The reason you can't just swap out validation is that the validation also helps define the database structure, like setting a field to be non-null, or non-blank, or having a specific length. Turning off "non-null", for example, could break the database structure.

命令对象是

Command objects, on the other hand, are designed to have their own unique set of validation rules. It's not the cleanest method (now you are tracking the same structure in more than one situation), but it's better in a lot of ways.

  • 它使您可以安全地接受输入参数,而不必担心设置了不应处理的内容.
  • 它创建了更整洁的控制器,因为验证逻辑都可以在Command Object中处理,而不能通过controller方法散布.
  • 它们使您可以验证对象上实际上不存在的属性(例如密码验证字段).

如果您认为确实需要多套约束,则很有可能 a)使域对象过于复杂,以表示超出其实际应有的更多信息(可能将其分解为多个-to-one相关对象)或 b)首先错误地设置了约束.†

If you think you really need multiple sets of constraints, you are most likely either a) over-complicating the domain object to represent more information than it really should (maybe break it up into several one-to-one related objects), or b) incorrectly setting the constraints in the first place.†

根据我的经验,通常是 a 发生在您觉得需要换掉约束时.

In my experience, usually it's a that happens when you feel the need to swap out constraints.

†话虽如此,(很少)有道理.但是在这种情况下,Command对象是最好的解决方案.

这篇关于如何在Grails中的单个域类上使用多个约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆