Checking a group of fields in a grails domain object

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()))
            {
                // They havent provided ANY feedback. Throw an error
                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

+3
source share
4
+1

/ ( , 2 ..)?

:

if ( (form.textarea1?.trim() ? 1 : 0) +
     (form.textarea2?.trim() ? 1 : 0) +
     (form.textarea3?.trim() ? 1 : 0) < 2) {
     err.rejectValue("atLeastTwo", "no.feedback")
     return false
}

" , /", if-statement?

Groovier...

if (!( (form.textarea1?.trim() ?: 0) ||
     (form.textarea2?.trim() ?: 0) ||
     (form.textarea3?.trim() ?: 0) )) {
     err.rejectValue("atLeastOne", "no.feedback")
     return false
}
+1

WRT, , . / . , http://www.zorched.net/2008/01/25/build-a-custom-validator-in-grails-with-a-plugin/ http://grails.org/plugin/constraints

grooviness . ?. null

if ( form.textarea1?.isAllWhitespace() &&
     form.textarea2?.isAllWhitespace() &&
     form.textarea3?.isAllWhitespace() )
     {
          // They havent provided ANY feedback. Throw an error
          err.rejectValue("atLeastOne", "no.feedback")
          return false
     }
0

All Articles