简体   繁体   English

Grails min约束日期验证

[英]Grails min constraint for date validation

I am a newbie in grails and groovy. 我是grails和groovy的新手。 I have a Project domain-class with start and end date. 我有一个具有开始和结束日期的Project域类。 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). 我想提出一个约束,指定结束日期需要大于开始日期(然后项目的另一个子对象需要让其startdate和enddate与父项目的日期一起验证)。 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. 唯一约束允许以这种方式链接两个属性,希望min / max约束允许这样做。 I have tried 我试过了

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

It throws an error saying the property startDate is not available on Project 它会抛出一个错误,指出属性startDate在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. val是字段的值, obj是对要验证的对象的引用。 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 ). 闭包可以包含您需要的任何逻辑,因此您可以按照您在问题中描述的方式扩展验证(通过访问您使用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. 如何做到这一点也可以在上面链接的文档中找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM