Alex Vargas
Alex Vargas

Reputation: 406

Getting bad date on Grails Prod App

I have a production application made with Grails 2.2.4 that was deployed some weeks ago, in that app I have a domain class like this:

class Date{

Date mDate;
static constraints = {
    mDate(nullable:false, blank:false, max: new Date());
} 

}

Desired behavior: When a user creates an object from this class, the attribute mDate should not be greater than today's date.

Real behavior: When the user tries to create an object, the application tells her that the attribute mDate should not be greater than the deployed date.

Example:

Deployed date: 01/Aug/2015

User tries to create an object with the attribute mDate = 02/Aug/2015, then the system complains it shouldn't be greater than 01/Aug/2015.

What is happening?

Upvotes: 1

Views: 40

Answers (1)

doelleri
doelleri

Reputation: 19682

Grails only evaluates constraints once and then uses the same value. This is problematic when using new Date() instead of a constant value.

In the Grails docs under Declaring Constraints:

Note that constraints are only evaluated once which may be relevant for a constraint that relies on a value like an instance of java.util.Date.

class User {
    ...
    static constraints = {
        // this Date object is created when the constraints are evaluated, not
        // each time an instance of the User class is validated.
        birthDate max: new Date()
    }
}

Instead, use a custom validator:

class User {
    ...
    static constraints = {
        birthDate validator: { it < new Date() }
    }
}

Upvotes: 4

Related Questions