Grails GORM整数验证 [英] Grails GORM integer validation
问题描述
我想对需要整数值的Domain Object值施加约束来防止小数点从输入的值。在视图中输入3.3会导致创建的对象的值为3.我希望验证错误会被踢回给用户,表明只有整数值是有效的。
class ADomainObject {
整数anInteger
}
Controller
def save(){
//注意:params [anInteger] =3.3
ADomainObject aDomainObject = new ADomainObject(params)
aDomainObject.save flush:true
}
aDomainObject.anInteger = 3的持久化结果
导致失败需要哪种类型的约束?我已经尝试使用范围约束[0..1000],无济于事。
您可以注册一个自定义整数
的属性编辑器仅允许严格的整数值。
类IntegerEditor扩展了java.beans.PropertyEditorSupport {
void setAsText(String text
value = Integer.parseInt(text) (org.springframework.beans.PropertyEditorRegistry registry){
registry.registerCustomEditor(Integer,new IntegerEditor())
}
}
,然后在resources.groovy中:
beans = {
customPropertyEditorRegistrar(CustomPropertyEditorRegistrar)
}
Environment: Grails 2.0.4, Java 1.6.0
I'd like to put a constraint on a Domain Object value requiring an integer value to prevent a decimal value from being entered. Entering 3.3 in the view results in the object being created with a value of 3. I was hoping for a validation error that would be kicked back to the user indicating only integer values are valid.
class ADomainObject {
Integer anInteger
}
Controller
def save() {
// Note: params["anInteger"] = "3.3"
ADomainObject aDomainObject = new ADomainObject(params)
aDomainObject.save flush:true
}
Result in the persistence of aDomainObject.anInteger = 3
What type of constraint would be needed to cause a failure? I've tried using a range constraint, [0..1000], to no avail.
You can register a custom property editor for Integers
to only allow strictly Integer values. The following will apply to binding all Integers.
class IntegerEditor extends java.beans.PropertyEditorSupport {
void setAsText(String text) {
value = Integer.parseInt(text)
}
}
class CustomPropertyEditorRegistrar implements org.springframework.beans.PropertyEditorRegistrar {
void registerCustomEditors(org.springframework.beans.PropertyEditorRegistry registry) {
registry.registerCustomEditor(Integer, new IntegerEditor())
}
}
and then in resources.groovy:
beans = {
customPropertyEditorRegistrar(CustomPropertyEditorRegistrar)
}
这篇关于Grails GORM整数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!