【问题标题】:Grails - Cannot add a custom validator for a property in the domain classGrails - 无法为域类中的属性添加自定义验证器
【发布时间】:2012-07-31 22:46:32
【问题描述】:

我正在尝试为字符串状态添加自定义验证器,它应该检查字符串国家/地区是否为“美国”,然后状态应为“其他”。如果 country 不是 "usa" 而 state 是 "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 和 groovy 的新手,希望能在此问题上提供任何帮助。

【问题讨论】:

    标签: grails grails-orm grails-domain-class customvalidator


    【解决方案1】:

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

    自定义验证器由一个最多占用三个 参数。如果闭包接受零个或一个参数,则 参数值将是被验证的值(“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' ) 
    }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      相关资源
      最近更新 更多