Andrey Yaskulsky
Andrey Yaskulsky

Reputation: 2516

custom validation messages on default validators

Suppose I have some domain class with default validators:

    class Employee {

        String name
        String primaryEmail
        String url

        static constraints = {
            name blank: false
            primaryEmail email: true, unique: true
            url blank: false, url: true

        }

    }

I want to define names of messages that should be returned in case of failure of validation, something like that:

    class Employee {

        String name
        String primaryEmail
        String url

        static constraints = {
            name blank: false 'employee.invalid.name'
            primaryEmail email: true, unique: true
            url blank: false, url: true 'employee.invalid.email' 

        }

    }

is it possible in some way? Thank you!

Upvotes: 0

Views: 273

Answers (2)

Segundo
Segundo

Reputation: 23

You can do this by defining custom validator. It is basically a closure that takes up to three params. So in your example you could write:

class Employee {

    String name
    String primaryEmail
    String url

    static constraints = {
        name validator: {
            if (!it) return ['employee.invalid.name']
        }
        primaryEmail email: true, unique: true
        url validator: {
            if (!it) return ['employee.invalid.email']
        }
    }

}

Note about custom validator closure: if there are no params provided then you can access value of the property with implicit it variable:

validator: {
   if (!it) ...
}

If you provide two params then first param is the property value, the second is the domain class instance being validated (e.g. so you can check other params)

validator: {val, obj ->
  if (val && obj.otherProp){...}
}

If you provide three params then first two are the same as two params version and and the third is the Spring Errors object:

validator: {val, obj, err ->
  if (val && obj.otherProp){...}
}

For more detailed explanation check out docs: http://grails.org/doc/latest/ref/Constraints/validator.html

Upvotes: 1

Joshua Moore
Joshua Moore

Reputation: 24776

Defining your own custom messages is actually quite simple. However, your approach here is incorrect.

First, take a look at the validation reference to get an understanding of how validation message codes are constructed.

Using your example, some of your custom messages would be:

employee.name.blank=Custom message about invalid employee due to blank
employee.url.blank=Another custom message about blank url
employee.url.url.invalid=Custom invalid url message

Messages are per constraint type, thus having one global message for each property isn't going to work. You will need to provide messages for each constraint that can fail.

Upvotes: 1

Related Questions