Grails GORM integer validation

♀尐吖头ヾ 提交于 2019-12-11 01:49:09

问题


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.


回答1:


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)
}



回答2:


Maybe you can use a custom validator like this:

static constraints = {
        anInteger validator: {
            //aDomainObject. anInteger.invalid.type
            if (!(it instanceOf Integer)) return ['invalid.type']
        }
    }


来源:https://stackoverflow.com/questions/12681441/grails-gorm-integer-validation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!