could not parse date unparseable date grails domain save



could not parse date unparseable date grails domain save
I ran into a little problem with Grails and validation today. I was parsing a date from a web post and kept getting a validation error.
My original code was as follows:
def job = new Job(params)
if (params?.expiryDate) {
    job.expiryDate = new Date().parse("MM/dd/yyyy", params.expiryDate)
} else {
    job.expiryDate = null
}
job.validate()
if (!job.hasErrors()){
    job.save(failOnError:true)
}
When i am trying to save job i am getting validation error "Failed to convert property value of type java.lang.String to required type java.sql.Date for property ; nested exception is java.lang.IllegalArgumentException: Could not parse date: Unparseable date: "
When I got the validation errors, I realized the date format was wrong and tried multiple ways to convert string to date object.
Seemed simple enough. But I kept getting validation errors on the date.
My domain clearly had a Date property, a I was creating a valid date and setting it. Answer nothing was wrong with with the value I parsed and set. Problem was in creating the application object in the first place. This chunk of code:
def job = new Job(params)
is implicitly calling validate and populating the errors object. Even though I was setting a valid value and calling validate later, the errors object had already been set and was not getting cleared.
Solution:
job.clearErrors()
Thats it . It works like a champ now!
Here is the full code :
def job = new Job(params)
job.clearErrors();
if (params?.expiryDate) {
    job.expiryDate = new Date().parse("MM/dd/yyyy", params.expiryDate)
} else {
    job.expiryDate = null
}
job.validate()
if (!job.hasErrors()){
    job.save(failOnError:true)
}
Source : http://jts-blog.com/ (Thanks to JT for saving my time)

Categories: