我正在尝试为String状态添加自定义验证器,该状态应检查字符串国家是否为“usa”,然后状态应为“Other”。如果国家不是“美国”而国家是“其他”那么它应该抛出错误。
此外,我想为国家/地区添加自定义验证程序以执行相同操作。
请在下面找到我的域类的代码。
package symcadminidp
import java.sql.Timestamp
import groovy.transform.ToString
@ToString
class Account {
static auditable = [ignore:['dateCreated','lastUpdated']]
String organization
String organizationUnit
String status
String address1
String address2
String zipcode
String state
String country
Timestamp dateCreated
Timestamp lastUpdated
Account(){
status = "ENABLED"
}
static hasMany = [samlInfo: SAMLInfo, contacts: Contact]
static mapping = {
table 'sidp_account_t'
id column: 'account_id', generator:'sequence', params:[sequence:'sidp_seq']
contacts cascade:'all'
accountId generator:'assigned'
organization column:'org'
organizationUnit column:'org_unit'
zipcode column:'zip'
dateCreated column:'date_created'
lastUpdated column:'date_updated'
}
static constraints = {
organization size: 1..100, blank: false
organizationUnit size: 1..100, blank: false, unique: ['organization']
//The organizationUnit must be unique in one organization
//but there might be organizationUnits with same name in different organizations,
//i.e. the organizationUnit isn't unique by itself.
address1 blank:false
zipcode size: 1..15, blank: false
contacts nullable: false, cascade: true
status blank:false
//state ( validator: {val, obj -> if (obj.params.country.compareTocompareToIgnoreCase("usa")) return (! obj.params.state.compareToIgnoreCase("other"))})
//it.country.compareToIgnoreCase("usa")) return (!state.compareToIgnoreCase("other"))}
}
}
当我尝试添加上面注释掉的代码时,我收到以下错误:
URI:/ symcadminidp / account / index 类:groovy.lang.MissingPropertyException 消息:没有这样的属性:类的参数:symcadminidp.Account
我是grails and groovy的新手,并希望对此问题有所帮助。
答案 0 :(得分:3)
验证程序(obj)的第二个值是帐户域类。
自定义验证器由一个最多需要三个的Closure实现 参数。如果Closure接受零个或一个参数,则 参数值将是被验证的参数值(在a的情况下为“it”) 零参数闭包)。如果它接受两个参数,则第一个是 值,第二个是要验证的域类实例。
http://grails.org/doc/latest/ref/Constraints/validator.html
你的验证器应该是
state validator: { val, obj ->
return ( obj.country.toLowerCase() == 'usa' ) ?
( val.toLowerCase() != 'other' ) :
( val.toLowerCase() == 'other' )
}