2012-07-31 84 views
2

我想添加一個自定義驗證器的字符串狀態,它應該檢查如果字符串國家是「美國」,那麼狀態應該是「其他」 。如果國家不是「美國」,國家是「其他」,那麼它應該拋出一個錯誤。Grails - 不能添加一個自定義驗證器的域類中的屬性

另外,我想爲國家添加一個自定義驗證器來做同樣的事情。

請在下面找到我的域名類的代碼。

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 /帳戶/索引 類別:groovy.lang.MissingPropertyException 消息:沒有這樣的屬性: params for class:symcadminidp.Account

我是grails和groovy的新手,希望對此問題有所幫助。

回答

3

您驗證器(obj)的第二個值是Account域類。

A custom validator is implemented by a Closure that takes up to three parameters. If the Closure accepts zero or one parameter, the parameter value will be the one being validated ("it" in the case of a zero-parameter Closure). If it accepts two parameters the first is the value and the second is the domain class instance being validated.

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

您的驗證應該像

state validator: { val, obj -> 
    return (obj.country.toLowerCase() == 'usa') ? 
      (val.toLowerCase() != 'other') : 
      (val.toLowerCase() == 'other') 
} 
+0

這完美的作品。謝謝! – 2012-08-01 03:23:56