1

Let's saying I have the following command:

@Validateable
class MyCommand {
    String cancel_url
    String redirect_url
    String success_url

    static constraints = {
        cancel_url nullable: false, validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
        redirect_url nullable: false, validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
        success_url nullable: false, validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
    }
}

Let's say I have some common validation I want to perform on any URL field (for instance, checking that the domain is allowed). What's the syntax to break this common validation code into a separate function instead of putting the same block in each validation closure?

Paul Erdos
  • 1,355
  • 2
  • 23
  • 47

1 Answers1

0

Did you try to inherit (or let's say implement) your command from several traits?

Trait CancelComponentCommand {
    String cancelUrl

    static constraints = {
        cancelUrl validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
    }
}

Trait RedirectComponenCommand {
    String redirectUrl

    static constraints = {
            redirectUrl validator: { url, obj ->
            //some specific validation
            //some common url validation
        }
    }
}

@Validateable
class MyCommand implements CancelComponentCommand, RedirectComponenCommand {

}

PS There is no need to set nullable: false, it's false by default. Also the code is much more readable if fields are written using camelCase.

Anton Hlinisty
  • 1,441
  • 1
  • 20
  • 35