0

I would like to build a customized validator in my Command object, to make sure the field email address of a form will not be empty if the notifyMe checkbox is selected.

Here is my latest attempt to implement it:

email(blank: true, nullable: true, email: true,
                  validator: {email, creditProviderCommand ->
                              if (creditProviderCommand.notifyMe == 'on')
                                    return email.size() > 0})

I have tried also with email != null and email != '' but it is not working in both cases, meaning that the form submission is accepted even with the notifyMe checkbox checked and the email address field left blank.

The code of the action handles the validation error properly (even unique constraint). Any idea of what I am doing wrong ?

Thank you very much for your help.

Alexandre Bourlier
  • 3,972
  • 4
  • 44
  • 76
  • What's the type of `notifyMe`, `boolean` or `String`? What value is actually assigned to it? I suppose `boolean` or `Boolean`, so you just need to check it for truth, not for `'on'`. – Victor Sergienko Sep 05 '11 at 11:47

1 Answers1

0

The code above looks fine to me. Are you 100% sure that creditProviderCommand.notifyMe == 'on' when the checkbox is checked?

the form submission is accepted even with the notifyMe checkbox

The form submission will always be accepted, even when there are validation errors. It is your responsibility to check for validation errors and decide what to do when validation fails, e.g.

def myAction = {MyCommand cmd ->

  if (cmd.validate()) {
    // code to be executed when validation succeeds
  } else {
    // code to be executed when validation fails
  }
}
Dónal
  • 185,044
  • 174
  • 569
  • 824
  • There actually is a bug, Grails allow email when containing only blank characters (email constraint). This is how I worked around this, using .trim() to exclude white spaces: validator: {email, creditProviderCommand -> if (creditProviderCommand.notifyMe) { if (!email) return email != null else return email.trim() != '' } } – Alexandre Bourlier Sep 06 '11 at 02:43