如何用grails命令对象编写日期验证器?

时间:2011-08-23 18:52:27

标签: validation grails command

我想在命令对象中添加日期表达式验证器,但我不确定正确的语法是什么......

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

1 个答案:

答案 0 :(得分:4)

您可以使用自定义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
        }
    }
}