【问题标题】:In a Grails domain object, is it possible to validate a field based on another field?在 Grails 域对象中,是否可以基于另一个字段验证一个字段?
【发布时间】:2012-05-17 22:50:12
【问题描述】:

我有一个如下所示的 Grails 域对象:

class Product {
    Boolean isDiscounted = false
    Integer discountPercent = 0

    static constraints = {
        isDiscounted(nullable: false)
        discountPercent(range:0..99)
}

我想向discountPercent 添加一个验证器,它只会验证isDiscounted 是否为真,如下所示:

validator: { val, thisProduct ->
    if (thisProduct.isDiscounted) {
        // need to run the default validator here
        thisProduct.discountPercent.validate() // not actual working code
    } else {
        thisProduct.discountPercent = null // reset discount percent
}

有人知道我该怎么做吗?

【问题讨论】:

  • 这正是你的做法,把它放在 discountPercent 属性上,你应该很高兴。什么是行不通的?你有什么例外吗?
  • discountPercent.validate() 不存在。
  • validate() 作用于整个域对象而不是单个字段,因此您需要 thisProduct.validate()
  • 是的,很抱歉,我浏览了您的实际域对象并假设 discountPercent 是另一个实体。
  • 您的意思是thisProduct.discountPercent = null 还是==?不要在验证器中设置值。您可以在 beforeInsertbeforeUpdate 中设置值。

标签: validation grails groovy grails-orm


【解决方案1】:

这或多或少是您需要的(在 discountPercent 字段中):

validator: { val, thisProduct ->
if (thisProduct.isDiscounted)
    if (val < 0) {
        return 'range.toosmall' //default code for this range constraint error
    }
    if (99 < val) {
        return 'range.toobig' //default code for this range constraint error

} else {
    return 'invalid.dependency'
}

你不能同时拥有一个依赖于其他东西的特殊验证器都有一个特殊的验证器,因为你不能在一个字段上运行单个验证器(据我所知),只有在单一属性上。但是,如果您对此属性进行验证,您将依赖自己并进入无休止的递归。因此我手动添加了范围检查。在您的 i18n 文件中,您可以设置 full.packet.path.FullClassName.invalid.dependency=Product not discounted 之类的内容。

祝你好运!

【讨论】:

  • 我强烈建议您放弃在验证器中将百分比设置为 null 的想法,验证器用于验证,而不是业务逻辑。在您的控制器或此代码所在的任何位置执行if(!product.validate()) { product.discountPercent = null } 类型的解决方案。
  • 谢谢,这很有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多