MVC 3 - “isDateTime”的验证不工作
我有 2 个日期时间字段,我使用日期选择器供用户选择日期。但是,由于它是一个文本框,用户仍然可以输入任何值并单击提交按钮。因此,我希望对日期时间文本字段进行验证,以检查提交的值是否是具有特定格式的日期时间。我尝试了这个:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
但是,即使我在文本框中输入“xxxxx”并提交,我也没有收到任何消息(注意:[必需]验证确实有效)
我的表单是这样的:
<div class="editor-label">
Storage Date
</div>
<div class="editor-field">
@Html.TextBox("StorageDate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "storagedate" })
@Html.ValidationMessageFor(model => model.StorageDate)
</div>
所以,我需要根据格式检查日期也..知道为什么它不起作用吗???
非常感谢任何帮助...谢谢...
I got 2 DateTime field and i use datepicker for user to choose a date. However, since it is a textbox, user can still enter any value and click the submit button. So, I wish to have validation on the DateTime textfield to check whether the value submitted is a DateTime with specific format. I tried this:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
However, I dint get any message even i input "xxxxx" in the textbox and submit (Note: the [Required] validation do work)
My form is like this:
<div class="editor-label">
Storage Date
</div>
<div class="editor-field">
@Html.TextBox("StorageDate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "storagedate" })
@Html.ValidationMessageFor(model => model.StorageDate)
</div>
So, I need check the Date according to the format also.. Any idea why it is not working???
Any help is really appreciated...Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将正则表达式注释添加到视图模型的属性中:
这是 REGEX 库的链接 - 您可以选择使用它们的表达式之一来验证日期。
You could add a regular expression annotation to the property of your view model:
Here is a link for a REGEX library - you may choose to use one of their expressions for validating date.
为了验证文本框中的值是否为有效日期,您需要添加带有日期格式正则表达式的
RegularExpressionAttribute
。我使用自定义属性和正则表达式来验证字符串的格式是否为 mm/dd/yyyy。用[日期]装饰属性,然后就完成了。
In order to validate that the value in the textbox is a valid date, you need to add a
RegularExpressionAttribute
with a regex for a date format. I use a custom attribute, with a regex to validate that a string is in the format mm/dd/yyyy.Decorate the property with [Date], and you're set.