Some experimentation on constraints in Grails 2.4.4 (based on the constraint documentation) leads me to the following conclusions:
- Use “nullable” instead of “blank”. The documentation says that “blank” is for strings, but Grails 2.4.4 doesn’t seem to pay any attention to that keyword. Setting “nullable” always works.
- If the field can be null, you can’t specify other constraints for when it is non-null. The logic is “null or must conform to set of standards X” is not supported through combinations of nullable and other constraints. You could get around this with custom validation or even regular expressions (using the constraints ‘validator’ or ‘matches’) if you wanted. (Perhaps there is another way to get around this – if so please share it!)
- All missingness is the same. All three missingness versions (empty string, null, and a missing parameter) have the same behavior. This is in contrast to some of the things I had been reading about empty strings in HTML forms being treated differently in Grails from actual null values, so I wonder if this is one of the pieces that has changed over time.
- “Optionals” is no longer supported. Testing suggested this, and it is backed up by this JIRA report.
The chart below gives the specifics as well as the take-aways.
Input for all tests was a String variable. When the string value “abc” was used, all tests pass. I excluded all the attempts with “optionals”, because all of those failed and the keyword is no longer supported.
Constraints | Test | Result | |||
Blank | Nullable | Size | Unique | ||
Not stated | Not stated | Not stated | Not stated | “” | Invalid |
Not stated | Not stated | Not stated | Not stated | null | Invalid |
Not stated | Not stated | Not stated | Not stated | missing | Invalid |
False | Not stated | Not stated | Not stated | “” | Invalid |
False | Not stated | Not stated | Not stated | null | Invalid |
False | Not stated | Not stated | Not stated | missing | Invalid |
True | Not stated | Not stated | Not stated | “” | Invalid |
True | Not stated | Not stated | Not stated | null | Invalid |
True | Not stated | Not stated | Not stated | missing | Invalid |
Not stated | True | Not stated | Not stated | “” | OK |
Not stated | True | Not stated | Not stated | null | OK |
Not stated | True | Not stated | Not stated | missing | OK |
Not stated | False | Not stated | Not stated | “” | Invalid |
Not stated | False | Not stated | Not stated | null | Invalid |
Not stated | True | 3..3 | Not stated | “” | Invalid |
Not stated | True | 3..3 | Not stated | null | Invalid |
Not stated | True | Not stated | True | “” | Invalid |
Not stated | True | Not stated | True | null | Invalid |