自定义Grails约束似乎不起作用

时间:2014-11-21 11:06:31

标签: grails grails-constraints

我一直在尝试在Grails项目中创建自定义约束(请参阅下面的约束代码)。

import org.codehaus.groovy.grails.validation.AbstractConstraint
import org.springframework.validation.Errors

class BuscaConstraint extends AbstractConstraint {

    public static final String CONSTRAINT_NAME = "busca"

    protected void processValidate(Object target, Object propertyValue, Errors errors) {
    }

    boolean supports(Class type) {
      return type && String.class.isAssignableFrom(type);
    }

    String getName() {
      return CONSTRAINT_NAME;
    }
}

如您所见,此约束实际上并未验证任何内容。相反,它只是一个标志来自定义脚手架生成中的属性渲染。 创建上面的类之后,我在Config.groovy文件中添加了以下行:

ConstrainedProperty.registerNewConstraint(BuscaConstraint.CONSTRAINT_NAME, BuscaConstraint.class)

..并将此约束添加到类的属性中:

class ThatClass {
  def someProperty
  static constraints = { someProperty (unique:true, busca: "nome") 
}

但是,如果我试图得到表达式的结果 ThatClass.constraints.someVariable.getAppliedConstraint("busca"), 我得到的只是null

我的方法基于this oneconstraint in Grails' github repo等博客文章(但我无法看到它们是如何配置的)。

我做错了什么? 有Grails的配置'最近自定义约束发生了变化?

2 个答案:

答案 0 :(得分:0)

看起来你的约束是好的。我在Url Without Scheme Validator Plugin UrlWithoutSchemeConstraint中使用了类似的东西,它在最近的Grails(2.3.x,2.4.x)中就像一个魅力。

但是,我从未试图在运行时访问它,因此我尝试调查此区域。例如,您是否尝试过ThatClass.constraints.someProperty.busca

答案 1 :(得分:0)

我也在Grails 2.4.4项目中使用约束作为标记。可以使用以下代码访问约束:

domainClass.constraints[p.name].getMetaConstraintValue("encodeAsRaw")

其中p.name是属性名称,“encodeAsRaw”是我的约束的名称。我在几个.gsp文件中成功使用此代码。

如果仅用作标记,则甚至不需要创建自定义约束类并进行注册。只需使用getMetaConstraintValue方法检查它的存在就足够了。

为了完整性,这是我的域类中的约束定义:

myProperty(nullable:true, blank:true, unique:false, maxSize:1000, encodeAsRaw:true)