Fletch
Fletch

Reputation: 5219

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

Upvotes: 5

Views: 6650

Answers (4)

James McMahon
James McMahon

Reputation: 49629

As you pointed out in your Jira link, I think the correct answer for this is to use the range constraint for Integers.

I think this is a simple as replacing size with range.

Upvotes: 0

Fletch
Fletch

Reputation: 5219

I found the answer whilst searching JIRA: http://jira.codehaus.org/browse/GRAILS-947. The doc is wrong.

We don't need minSize, maxSize and size constraints for numeric fields anymore since this functionality is on min, max and range constraints respective. So we marking these constraints (for numeric fields only) as deprecated in 0.5 and will remove it in 0.6.

Looks like it's up to the custom validator.

Upvotes: 2

Dave Klein
Dave Klein

Reputation: 207

You can also use max to constrain an integer like myIntProp(max:9999999)

Upvotes: 1

Robert Munteanu
Robert Munteanu

Reputation: 68268

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

Upvotes: 2

Related Questions