Search code examples
validationgrailsconstraintsgrails-orm

Use size constraint with Integer in Grails


The reference doc says that the size constraint:

Uses a Groovy range to restrict the size of a collection or number or the length of a String.

When I put a size constraint on an integer, I get a warning

Property [prop] of domain class TheClass has type [java.lang.Integer] and doesn't support constraint [size]. This constraint will not be checked during validation.

Is the doc wrong?

I know I could use range but it would generally be easier to be able to specify the amount of digits in the number rather than the actual value (like a social security number must have 7 digits or whatever it is, rather than making a range of 1000000 - 9999999).


Solution

  • If you want the number of digits, make sure it's positive and has a certain length:

    myInteger( validator: {
       return it > 0 &&  (it.toString.length) == 7
    })