[英]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.