问题
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