raffian
raffian

Reputation: 32066

How to write a date validator with grails command object?

I want to add a date expression validator in my command object, but I'm not sure what's the correct syntax...

class UserController {
    …
}
class DateServiceCommand {
    String date    //valid format is DD-MMM-YYYY, 01-APR-2011
    static constraints = {
        date(blank:false, ??? )
    }
}

Upvotes: 1

Views: 2608

Answers (1)

Rob Hruska
Rob Hruska

Reputation: 120286

You can use a custom validator:

import java.text.*

class DateServiceCommand {
    String date
    static constraints = {
        date blank: false, validator: { v ->
            def df = new SimpleDateFormat('dd-MMM-yyyy')
            df.lenient = false

            // parse will return null if date was unparseable
            return df.parse(v, new ParsePosition(0)) ? true : false
        }
    }
}

Upvotes: 4

Related Questions