Localizing validation (error) messages in Grails
I try to localize error messages from the Domain classes. This is possible with the default error messages, e.g.:
default.blank.message=Property [{0}] cannot be blank
and localized attribute names, e.g.:
customer.address.label=Customer address
Where "Customer" is my domain class and address is its attribute.
My problem is that I can't localize some attributes because I need specific error messages. E.g:
has.to.be.a.number=Property [{0}] has to be a number
contingent.size.label=Contingent size.
But the message I get is "Property [size] has to be a number" instead of "Property [Contingent size] has to be a number".
The messages I cant localize are following:
- Property [{0}] has to be a number
- Property [{0}] has to be a valid date // I can't use g:datePicker in this context
I add some other example with some other domain class which also doesn't work
package cz.quanti.spaportal.touristOffice
import ...
class Touri开发者_如何学JAVAstOffice {
String customerNumber
int minimalContingent
Address address
User user
ContactPerson contactPerson
static hasMany = [contingents: Contingent]
static constraints = {
customerNumber(unique:true, nullable: true, blank: true)
user(nullable: true, blank: true)
contactPerson(nullable: false)
minimalContingent(min: 0)
address(nullable: false)
}
Only the "minimalContingent" is not localized: (the message is localized and the minimal attribute is not) Property [minimalContingent] has to be a number.
If you are having problem with validation messages you can always check the codes for the validation errors using the errors
collection on an instance.
Customer c = ...
c.validate()
c.errors.each { println it }
c.errors.getFieldError("address").codes.each { println it }
c.errors.getFieldError("address").defaultMessage
Write a unit test to check the codes to localise the messages.
Make sure you're using the domain class package in your definitions. Also check your capitalization; I'm not sure if it makes a difference, but my successful messages.properties
using labels have looked akin to the following:
// messages.properties
com.example.Customer.address.label=Customer address
com.example.Contingent.size.label=Contingent size
// or if you're using the default package
Customer.address.label=Customer address
...
After your update, can you clarify something? Do you have the following in your
messages.properties
:
cz.quanti.spaportal.touristOffice.TouristOffice.minimalContingent.label=...
If not, does it work if you add it?
I think that the whole path to the attribute (without "label" in the end) should work for you. Looks like this:
com.example.Customer.homeAddress=Customer address
remember to use lowercase and uppercase where they are needed!
精彩评论