Grails 3 在运行时访问 Grails 域约束

Grails 3 Accessing Grails domain constraints at runtime

我曾经像这样在我的 gsp 中访问 grails 2 约束:

${MyDomainClass.constraints.myProperty.inList.collect{it.name()}} 

它不再适用于 Grails 3

这种方式在 Grails 2 中有效,现在仍然有效...

grailsApplication.getArtefact('Domain',
    'MyDomainClass').getConstrainedProperties().myProperty.inList.collect{it.name()}

see GrailsDomainClass API

在 Grails 3.0 中,域和命令对象使用特征 grails.validation.Validateable (可以找到源代码 here。该特征使您可以通过提供以下方法来访问约束。

static Map<String, ConstrainedProperty> getConstraintsMap();

为了访问您在域或命令对象上调用该方法的约束。以下示例访问名为 day.

的域对象 属性 上的 nullable 约束
domainObject.getConstraintsMap()['day']['nullable']