0
votes

I am currently working on a Grails application and I want to change the default error messages that are display for objects in my domain model. I believe I have done everything correct but maybe someone can help me solve this issue, code below:

Domain Model:

class Details {

    long mobileNo
    String name
    static constraints = {
    mobileNo(blank:false, maxsize:12, matches:"44[0-9]{10}")
    }
}

messages.properties

sms.mobileNo.matches.invalid=You must enter a correct mobile number in {0}

View

<g:hasErrors bean="${detailsInstance}">
    <div class="alert error">
        <g:renderErrors bean="${detailsInstance}" as="list" />
    </div>
</g:hasErrors>

Now when the create clicked on the page it goes to the following controller functions:

def details = new Details(params)

        if (details.validate()) {

}
else{
            render view: 'create', model: [detailsInstance: details]

        }

Now I would expect the application to work like this: One the wrong data is passed to the controller it sees it is not valid and then passes the model with errors back to the same view. Then the error messages are pulled where the data is incorrect from the messages.properties file. However where I expect to see this:

You must enter a correct mobile number in [mobileNo]

I instead see this:

Failed to convert property value of type java.lang.String to required type long for property mobileNo; nested exception is java.lang.IllegalArgumentException: Could not parse number: Unparseable number: "gg"

Can someone please help me to generate custom messages for validation in order to display helpful messages to users? Thanks

2

2 Answers

2
votes

The problem is, that before validation, binding tries to bind your value 'gg' to a long.

Your constraints also says:

mobileNo(blank:false, maxsize:12, matches:"44[0-9]{10}"

thus you expect it to be a string, but it's defined as a long.

Try changing your mobileNo to a String type.

0
votes

Look into your stacktrace a little deeper and it will probably tell you the line number in which the error is being thrown. My guess is that it is throwing the exception on the following line...

new Details(params)

This is because you are not checking the input before grails is trying to convert 'gg' to a long, which will not work. In my opinion you have four options here...

  1. Change mobileNo to a String
  2. Validate the params before doing new Details(params) (not recommend)
  3. Use javascript/jquery to only allow numeric values in the input.
  4. I remember that there where some additional plugs to add to grails for remote validation or something like that but I can't remember them off the top of my head. However, I would just build my own using jquery (or whatever).

Enjoy!