gpt4 book ai didi

Grails - 无法为域类中的属性添加自定义验证器

转载 作者:行者123 更新时间:2023-12-02 13:58:01 24 4
gpt4 key购买 nike

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

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

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

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 的新手,希望对这个问题有任何帮助。

最佳答案

验证器 (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' )
}

关于Grails - 无法为域类中的属性添加自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11750130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com