2

我正在尝试为字符串状态添加一个自定义验证器,它应该检查字符串国家是否是“美国”,那么状态应该是“其他”。如果国家不是“美国”而国家是“其他”,那么它应该抛出一个错误。

另外,我想为国家添加一个自定义验证器来做同样的事情。

请在下面找到我的域类的代码。

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 和 groovy 的新手,希望能在这个问题上提供任何帮助。

4

1 回答 1

3

验证器 (obj) 的第二个值是 Account 域类。

自定义验证器由最多三个参数的闭包实现。如果闭包接受零或一个参数,则参数值将是被验证的值(在零参数闭包的情况下为“它”)。如果它接受两个参数,第一个是值,第二个是正在验证的域类实例。

http://grails.org/doc/latest/ref/Constraints/validator.html

您的验证器应该类似于

state validator: { val, obj -> 
    return ( obj.country.toLowerCase() == 'usa' ) ?
           ( val.toLowerCase() != 'other' ) : 
           ( val.toLowerCase() == 'other' ) 
}   
于 2012-07-31T23:53:30.940 回答