I have a command object that captures a feedback form with 3 text areas.
class FeedbackCommand {
String textarea1
String textarea2
String textarea3
String username
static constraints = {
textarea1(nullable:true, blank:true)
textarea2(nullable:true, blank:true)
textarea3(nullable:true, blank:true)
username(nullable:false, blank:false)
}
}
I would like to make sure that at least ONE of the text fields is full.
I came up with the addition of a fake field to the "restriction" field, and then performed a bunch of object checks in the custom validator for that field. If, after examining myself, I don’t find what I want, I make a mistake.
Now I am doing this:
class FeedbackCommand {
String textarea1
String textarea2
String textarea3
boolean atLeastOne = true
String username
static constraints = {
textarea1(nullable:true, blank:true)
textarea2(nullable:true, blank:true)
textarea3(nullable:true, blank:true)
atLeastOne(validator: { boolean b, FeedbackCommand form, Errors err ->
if (b) {
if ( (form.textarea1==null || form.textarea1?.isAllWhitespace()) &&
(form.textarea2==null || form.textarea2?.isAllWhitespace()) &&
(form.textarea3==null || form.textarea3?.isAllWhitespace()))
{
err.rejectValue("atLeastOne", "no.feedback")
return false
}
}
return true
})
username(nullable:false, blank:false)
}
}
Is there a better way
- check related / group of fields (at least one cannot be empty, 2 must have values, etc.)?
- a more attractive way of expressing "at least one must be null / blank" rather than my heavy if-statement block?
thank
source
share