简体   繁体   English

如何创建所需的DateTime模型属性?

[英]How can I make a DateTime model property required?

I have a model that has a datetime property and I want to make sure that in the view, the form can't be submitted unless that editor for has a value. 我有一个具有datetime属性的模型,我想确保在视图中,除非该编辑器具有值,否则无法提交表单。

employee {
 [DataType(DataType.Date)]
 [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
 [Required] // <- this isn't doing anything for me???
 public DateTime DateOfBirth {get;set;}
}

is there an annotation I can use for this or do I have to use javascript in the page? 有没有我可以使用的注释,或者我必须在页面中使用javascript?

or is there another solution? 还是有另一种解决方案?

Update - 更新 -

When I clear out the date editor, I get the following in my editor box: 当我清除日期编辑器时,我在编辑框中得到以下信息:

mm/dd/yyyy

when I submit this, does this count as null or what? 当我提交这个,这算是空的还是什么? Making the DateTime property nullable didn't fix my issue, theres no validation taking place when I submit a form that has mm/dd/yyyy for the date 使DateTime属性可以为空可以解决我的问题,当我提交一个日期为mm / dd / yyyy的表单时,没有进行验证

Your problem is that DateTime always has a value . 您的问题是DateTime 始终具有值

You'll need to make it a nullable DateTime : 你需要让它成为可以为空的 DateTime

[Required]
public DateTime? DateOfBirth { get; set; }

Now your property will be null when no value is present and your Required attribute will behave as expected. 现在,如果没有值,您的属性将为null,并且您的Required属性将按预期运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Web API中的模型中禁用属性的必填属性? - How can I disable required attribute on a property in a model in web api? 如何使 DateTime 不需要? - How do I make DateTime not required? 如何让 Prism 的 DelegateCommand 观察子视图模型的属性? - How can I make Prism's DelegateCommand observe a child view-model's property? 为什么不能禁用datetime必需属性的MVC模型? - why can not disable datetime required attributes MVC model? 如何在控制器MVC中添加必需的模型属性? - How to add required to model property in controller mvc? 如何使用CSOM模型获取SharePoint服务器日期时间? - How can I get SharePoint server datetime using CSOM model? 如何在 c# 中创建所需的属性? - How to make a property required in c#? 如何在POST上创建必需的属性,但在PUT请求上不设置 - How to make a property required on POST but not on PUT requests 如何只存储日期时间的日期部分。 今天属性到SQL Server表的datetime列? - How can I store only the date portion of the datetime. Today property to a SQL Server table datetime column? 如何从具有Datetime属性的对象的IEnumerble列表中的Ajax调用正确序列化Datetime - How can I correctly serialize Datetime from an Ajax call inside an IEnumerble list of objects that have a Datetime property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM