【问题标题】:Property startDate must be a valid Date error in Grails属性 startDate 必须是 Grails 中的有效日期错误
【发布时间】:2016-05-13 22:24:47
【问题描述】:

我遇到了与here 提到的相同的问题,但是当我厌倦了解决方案中的内容时,我仍然遇到相同的错误:

属性 startDate 必须是有效的 Date 属性 endDate 必须是 有效日期

这是我的域名:

class EmpRef {
    String workName
    String title
    Date   startDate
    Date   endDate
    String reasonForLeaving
    String directMgrName
    String directMgrTitle
    String directMgrTelephone
}

这是我的保存操作:

def save(EmpRef empRefInstance) {
    empRefInstance.startDate=Date.parse('dd-MM-yyyy',params.startDate)
    empRefInstance.endDate=Date.parse('dd-MM-yyyy',params.endDate)
    if (empRefInstance == null) {
        notFound()
        return
    }

    if (empRefInstance.hasErrors()) {
        respond empRefInstance.errors, view:'create'
        return
    }

    empRefInstance.save flush:true
}

GSP 中的 jQuery 代码:

$('.datePicker').datepicker({
    changeYear: true,
    changeMonth: true,
    autoSize: true,
    dateFormat: "dd-mm-yy",
    maxDate: "0y",
    showAnim: "show",
    yearRange:'c-70:c+0'
});

【问题讨论】:

  • dd-MM vs dd-mm 试图看看有什么区别?月与分钟

标签: validation grails


【解决方案1】:

如果EmpRef 是方法的参数,它会根据请求自动绑定。这会导致startDateendDate 出现错误。在这些列上设置值后,您需要执行 empRefInstance.validate() 而不是 empRefInstance.hasErrors() 才能在域中获得新的验证结果。

另外,因为您检查empRefInstance 是否为空 设置开始和结束日期后,如果此对象为空,您将在前面的行中收到 NullPointerException,因此应在代码的前面完成检查空

【讨论】:

  • 我在调试的时候发现startDateendDateempRefInstance中是null ,虽然它应该在这里设置<input type="text" class='datePicker' name='startDate' >,这可能是什么原因?
  • null 中的params.startDate 吗?
  • no params.startDateparams.endDate 不为空,当我打印 empRefInstance.properties 时 startDate 和 endDate 为空
  • 我在解析 startDate 后也发现它的值是 Sun May 01 00:00:00 EEST 2016 虽然格式是 dd-MM-yyyy ,所以我认为问题出在解析中。
  • empRefInstance 具有空属性,因为绑定失败。您可以在域/命令属性上设置格式,这些属性应该用于解析来自客户端的值 - 检查文档中的 Date Formats For Data Binding 章节。此外,如果您发送的值看起来不起作用,您必须在客户端设置正确的格式
猜你喜欢
  • 1970-01-01
  • 2012-03-07
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
  • 2015-08-11
  • 2020-09-24
  • 1970-01-01
相关资源
最近更新 更多