Grails GORM整数验证 [英] Grails GORM integer validation

查看:76
本文介绍了Grails GORM整数验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:Grails 2.0.4,Java 1.6.0

我想对需要整数值的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆