When using command objects like:
class UserCommand {
String name
static constraints = {
name blank: false, unique: true, minSize: 3
}
}
you can use them to validate objects without making them persistent. In my case I would validate for a persistent class User.
In controller:
def save(UserCommand cmd) {
if(!cmd.validate()) {
render view: "create", model: [user: cmd]
return
}
def user = new User()
user.name = cmd.name
user.save()
redirect uri: '/'
}
in messages.properties:
user.username.minSize.error=Please enter at least three characters.
userCommand.username.minSize.error=Please enter at least three characters.
When using custom validation messages you have to write the message codes for each error twice. One for the User class and another for the UserCommand class.
Is there a way how I can have only one message code for each error?
importFrom User
in constraints forUserCommand
.But no it cannot achieve the goal. Finally,I think you have to have both the messages available. Refer Validation and Internationalization where it particularly says about Class name.Unless there is another way,I feel you have to stick to above in order to apply validation in Command Object and in Domain Object.Inheritance may be an option where I am skeptical. – Korey