提问人:Jun Rikson 提问时间:9/1/2023 更新时间:9/1/2023 访问量:14
MVC5 验证程序错误,日期和日期时间在同一页面中
MVC5 Validator Error With Date and DateTime in same page
问:
我的模型中有一个日期和一个日期时间字段:
[Display(Name = "Tanggal")]
[Required(ErrorMessage = "Tanggal harus diisi.")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
[Display(Name = "Waktu Penumpukan")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:DD/MM/YYYY HH:mm:ss}", ApplyFormatInEditMode = true)]
public DateTime StackingDate { get; set; }
我使用 bootstrap datetimepicker 作为 DateTime 字段,使用 HTML5 日期选择器作为我的日期字段。
<div class="form-group">
<div class="col-md-12">
@Html.LabelFor(model => model.Date)
@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
@Html.LabelFor(model => model.StackingDate)
<div id="datetimepicker1" class="input-group date">
@Html.TextBoxFor(model => model.StackingDate, new { @class = "form-control" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
@Html.ValidationMessageFor(model => model.StackingDate, "", new { @class = "text-danger" })
</div>
</div>
我正在使用 moments 并修改 javascript 中日期时间格式的已知错误
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD/MM/YYYY HH:mm:ss", true).isValid();
}
我的 DateTimePicker JavaScript 启动如下所示:
$('#datetimepicker1').datetimepicker({
format: 'DD/MM/YYYY HH:mm:ss'
});
我没有为日期字段使用引导日期时间选择器,因为我使用的是 HTML5 默认日期。它对日期时间字段工作正常,但我收到了日期错误。
字段 Tanggal 必须是日期。
如果我删除验证器,它对日期工作正常,但对日期时间字段有同样的错误。
答:
0赞
Jun Rikson
9/1/2023
#1
我发现验证器可以按id过滤
$.validator.methods.date = function (value, element) {
if (element.id === "Date") {
// For the "Tanggal" field, validate using HTML5 format
return this.optional(element) || moment(value, "YYYY-MM-DD", true).isValid();
} else {
// For the "StackingDate" field, validate using custom format
return this.optional(element) || moment(value, "DD/MM/YYYY HH:mm:ss", true).isValid();
}
};
评论