grails为hasErrors添加验证错误 [英] grails add validation error to hasErrors
问题描述
我想知道如何将自定义错误添加到hasErrors方法,以便gsp发现错误。我的代码到目前为止。
def recoverySetup = new RecoverySetup(params)
$ b $ def onesolOrgkey = OnesolOrgkeyInfo。 get(new OnesolOrgkeyInfo(params));
$ b $ if(onesolOrgkey!= null){
recoverySetup.setOneSolOrgkey(onesolOrgkey)
} else {
recoverySetup.errors.reject('orgkey','You must提供有效的组织键')
}
recoverySetup.validate()
if(recoverySetup.hasErrors()){
render view:' create',model:[recoverySetupInstance:recoverySetup]
return
}
正如Danilo所说,您可能希望为您的域类添加一个约束来为您做。
了解有关约束的更多信息 http://grails.github.io/grails-doc /2.2.x/guide/single.html#constraints 和 http://grails.github.io/grails-doc/2.2.x/ref/Constraints/Usage.html 。
如果无论出于什么原因你真的想要t o添加约束无法涵盖的自定义错误(我现在无法想象一个案例,但这并不意味着它不存在:-),您仍然可以以非常类似于你发布:
$ pre $实例.errors.rejectValue(fieldName,errorCode,message,defaultMessage)
instance.errors.reject (errorCode,message,defaultMessage)
第一个拒绝一个具体的字段,通常是第二个bean。但请牢记当您再次调用 validate
时,此错误将被重置。
另外,您可以在grails中自动显示错误:
< g:hasErrors bean =$ {instance }>
< g:renderErrors bean =$ {instance}/>
< / g:hasErrors>
查看所有选项: https://grails.github.io/grails-doc/2.2.x/ref/Tags/hasErrors.html
I'd like to know how to add a custom error to the hasErrors method so that the gsp picks up the error. My code thus far.
def recoverySetup = new RecoverySetup(params)
def onesolOrgkey = OnesolOrgkeyInfo.get(new OnesolOrgkeyInfo(params));
if(onesolOrgkey != null) {
recoverySetup.setOneSolOrgkey(onesolOrgkey)
} else {
recoverySetup.errors.reject('orgkey', 'You must provide a valid Org Key')
}
recoverySetup.validate()
if(recoverySetup.hasErrors()) {
render view: 'create', model: [recoverySetupInstance: recoverySetup]
return
}
As Danilo says, you probably want to add a constraint to your domain class to do that for you.
Learn more about constraints in http://grails.github.io/grails-doc/2.2.x/guide/single.html#constraints and http://grails.github.io/grails-doc/2.2.x/ref/Constraints/Usage.html .
If for whatever reason you really want to add a custom error that cannot be covered by the constraints (I can't imagine a case right now, but that doesn't mean it doesn't exists :-), you can still do it in a very similar fashion of what you posted:
instance.errors.rejectValue(fieldName, errorCode, message, defaultMessage)
instance.errors.reject(errorCode, message, defaultMessage)
The first rejects a concrete field, the second the bean in general. But bear in mind this errors will be reset when you invoke validate
again.
Also, you can display the errors of a bean automatically in grails with:
<g:hasErrors bean="${instance}">
<g:renderErrors bean="${instance}" />
</g:hasErrors>
See all the options here: https://grails.github.io/grails-doc/2.2.x/ref/Tags/hasErrors.html
这篇关于grails为hasErrors添加验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!