日期验证的Grails min约束 [英] Grails min constraint for date validation

查看:98
本文介绍了日期验证的Grails min约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Grails和Groovy中是一个新手。我有一个具有开始和结束日期的Project域类。我想要放入一个约束,指定结束日期需要大于开始日期(然后,项目的另一个子对象需要使用父项目的日期来验证其startdate和enddate)。这是可能的最小约束,还是我必须把它放在其他地方?唯一约束确实允许以这种方式链接两个属性,希望最小/最大约束允许这样做。
我试过了

$ p $ startDate(blank:false)
endDate(blank:false,min:' startDate')

它引发一个错误,说明属性startDate在Project

上不可用

解决方案

尝试使用自定义验证器:

 静态约束= {
endDate(验证者:{val,obj - >
val?.after(obj.startDate)
})
}

val 是字段的值, obj 是对被验证对象的引用。闭包可以包含任何您需要的逻辑,所以您可以按照您在问题中描述的方式扩展验证(通过使用 obj 访问您引用的子对象) 。



自定义验证器非常灵活。查看文档。理想情况下,您需要返回自定义消息;如何做到这一点,也可以在上面链接的文档中找到。


I am a newbie in grails and groovy. I have a Project domain-class with start and end date. I want to put in a constraint specifying that the end date needs to be greater than the start date(and then further another child object of project needs to have its startdate and enddate validate with the parent Project's dates). Is this possible with the min constraint or do I have to put it elsewhere? Unique constraint does allow two properties to be linked that way, hoping min/max constraints allow that. I have tried

startDate(blank:false)
endDate(blank:false, min:'startDate')

It throws an error saying the property startDate is not available on Project

解决方案

Try using a custom validator:

static constraints = {
    endDate(validator: { val, obj ->
        val?.after(obj.startDate)
    })
}

val is the value of the field and obj is a reference to the object being validated. The closure can contain whatever logic you need, so you can extend your validation in the way you're describing in your question (by accessing the child objects you refer to using obj).

The custom validator is pretty flexible. Have a look at the documentation. Ideally you'll want to return a custom message; how to do that can also be found in the docs linked above.

这篇关于日期验证的Grails min约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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