【问题标题】:Custom Grails Constraint doesn't seem to work自定义 Grails 约束似乎不起作用
【发布时间】:2014-11-21 11:06:31
【问题描述】:

我一直在尝试在 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 的自定义约束的配置最近有变化吗?

【问题讨论】:

    标签: grails grails-constraints


    【解决方案1】:

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

    但是,我从来没有尝试在运行时访问它,所以我会尝试调查这个区域。比如你试过ThatClass.constraints.someProperty.busca吗?

    【讨论】:

    • 在 grails 4 中以访问域类的匹配约束为例,它是 ThatClass.constrainedProperties.someProperty.matches - 我认为它已经按照答案 constraints 现在更改为 constraintProperties
    【解决方案2】:

    我还在 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2021-10-29
      相关资源
      最近更新 更多