我正在使用grails 2.5.1
。
在数据库中,我有近百个字段(例如:card_no、card_user、user_name
等)。
默认情况下,验证会显示错误消息:property card_no can not be null
但是,我要将其更改为:property Card No can not be null
,我需要在 message.property
中定义该错误。我有很多字段,为每个字段定义错误消息
需要时间。
有没有可能的方法来定义该字段的约束
?
如:card_no(nullable: false, range: 0..19, validator: { val, obj -> return 'abc' })
然后我可以轻松使用默认验证
我尝试了其他帖子中的代码,但语法似乎有错误。
任何解决方案将不胜感激。谢谢。
最佳答案
如果您使用脚手架
或使用g:message
来呈现错误/验证消息,那么覆盖
g
命名空间中的message
标签可以实现您想要的效果。
您不需要在消息文件中添加任何自定义 validator 或任何消息。您需要做的就是创建一个 TagLib
,它扩展 ValidationTagLib
并覆盖 message
闭包。
例如,在您的特定情况下,如果您只是想让字段名称在验证异常时更具可读性,您可以执行以下操作
class ApplicationTagLib extends ValidationTagLib {
Closure message = { attrs ->
def error = attrs.error
if(error && error instanceof FieldError) {
//arguments[0] should be the field name
error.arguments[0] = error.arguments[0].capitalize().replaceAll(/([a-z])([A-Z])/, '$1 $2')
}
super.message.call(attrs)
}
}
关于java - Grails 验证中的自定义字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32838033/