Roman
Roman

Reputation: 66156

How to compose Grails validation messages?

I have a simple domain entity:

package shoesshop

class Brand {

    String name
    String description
    String logoImageURL

    static constraints = {
        name(blank: false)
        logoImageURL(nullable: true)
    }
}

When I try to save a new brand with null value as its name, I want to render a message which says that 'Name must be specified'.

I tryied to add a property to messages.properties:

brand.name.nullable=Brand name must be specified  

But it's not picked up automatically. How should I retrieve it from there? I looked at brand.errors and it contains just a default message

Property [{0}] of class [{1}] cannot be null.

It also contains a set of error codes, one of which is brand.name.nullable.

Upvotes: 0

Views: 2284

Answers (3)

Sergey Orshanskiy
Sergey Orshanskiy

Reputation: 7054

I am using Grails 2.2.3. For me it works when I am using

brands.name.blank=The name cannot be empty

Now if I refresh the page ".../appname/controllername/save" after getting this error, I get

Property [name] of class [class ...] cannot be null

This message can be changed with

brands.name.nullable=The name cannot be null (do not refresh the page!!!)

Upvotes: 0

Kelly
Kelly

Reputation: 3709

It's strange to me that the nullable error message is showing up when you don't have the nullable constraint. In the docs for blank and nullable it clearly shows that nullable is different than blank and have separate messages.

Try

brand.name.blank

I also seem to have to add the .error to get things to work correctly:

brand.name.blank.error or brand.name.nullable.error

Upvotes: 1

Alex Vargas
Alex Vargas

Reputation: 406

Have you tried?:

if(brand.name==null)
{
    flash.message = message(code: 'brand.name.nullable',default:'Brand name must be specified.');
    render(view: "create", model: [brand:brand])
    return
}

You can try to change the message (don't know how this will perform with your entire app) of "default.null.message" to

{1} {0} must be specified

Upvotes: 2

Related Questions