简体   繁体   English

DateTime接受超过4位数字的年份

[英]DateTime accepts more than 4 digits for year

In my test application I have a datetime field defined as such: 在我的测试应用程序中,我有一个datetime字段,其定义如下:

[Required(ErrorMessage = "This is required")]
[Display(Name = "test date:")]
[DataType(DataType.Date)]        
[DisplayFormat(DataFormatString = "{0:dd/MMMM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? date1 { get; set; }

and in my view: 在我看来:

@Html.EditorFor(
    model => model.date1,
    new {
        htmlAttributes = new {
            @Value = Model.date1 != null ? Model.date1.Value.ToString("yyyy-MM-dd") : ""
        }
    })
@Html.ValidationMessageFor(model => model.date1, "", new { @class = "text-danger" })

Everything works fine but when I enter a date like 10/03/19999 (dd,MM,yyyyy), the application breaks, obviously the date I've entered is wrong but i'm not sure how to action the error. 一切正常,但是当我输入类似10/03/19999(dd,MM,yyyyy)的日期时,应用程序中断,显然我输入的日期是错误的,但是我不确定如何解决该错误。 I've tried using datetime.tryparse to postback on failure but then i lose what i filled the form in with. 我尝试使用datetime.tryparse失败时进行回发,但是随后我丢失了填写表单的内容。

Update: 更新:

Following quadzz solution, I've tried: 按照Quadzz解决方案,我尝试了:

[Required(ErrorMessage = "This is required")]
[Display(Name = "test date:")]
[DataType(DataType.Date)]
[Range(typeof(DateTime), "1/1/1900", "31/12/2000", ErrorMessage = "Value for {0} must be between {1} and {2}")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]

but it still doesn't work. 但它仍然不起作用。

Try ranging your datetime field. 尝试更改日期时间字段。 Reference here: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx 此处参考: https : //msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.rangeattribute.aspx

Example: 例:

    [Range(typeof(DateTime), "1/1/2000", "1/1/2010",
        ErrorMessage = "Value for {0} must be between {1:d} and {2:d}")]
    [DataType(DataType.Date)]

Perform client side validation before sending data to server. 在将数据发送到服务器之前执行客户端验证。 Though server side validation is also required your scenario could be handled by client side validation to do so include following js files in layout file 尽管还需要服务器端验证,但您的方案可以由客户端验证处理,以在布局文件中包括以下js文件

  1. jquery jQuery的
  2. jquery.validate jquery.validate
  3. jquery.validate.unobtrusive jquery.validate.unobtrusive

So your view should be like 所以你的观点应该像

@Html.EditorFor(
    model => model.date1,
    new {
        htmlAttributes = new {
            @Value = Model.date1 != null ? Model.date1.Value.ToString("yyyy-MM-dd") : "",
            @Readonly="readonly"
        }
    })
@Html.ValidationMessageFor(model => model.date1, "", new { @class = "text-danger" })

I have made Editor readonly so that user picks date from datepicker library (manual date entry is prohibited)[Though it can be easily bypassed] 我已将编辑器设为只读,以便用户从datepicker库中选择日期(禁止手动输入日期)[尽管可以轻松绕过它]

If client side validation is passed or client submit data by disabling javascript you need to perform server side validation which can be done in controller by checking ModelState 如果通过了客户端验证或通过禁用javascript来提交数据,则需要执行服务器端验证,这可以通过检查ModelState在控制器中完成

[HttpPost]
public ActionResult Employee(EmployeeModel employee)
{
  if(ModelState.IsValid)
  {
    //Everything is good to process
  }
  return View(employee);//returns view with model error if any
}

A couple of solutions: 几个解决方案:

Add client side validation to check the date before sending it to the server (and of course keep the server validation you do now as well). 添加客户端验证以检查日期,然后再将其发送到服务器(当然也要保留您现在执行的服务器验证)。 Doing this you reduce your problem to an almost insignificant number of cases (those users who doesn't have javascript enabled and input a wrong date). 这样做可以将您的问题减少到几乎无数的情况(那些未启用JavaScript并输入错误日期的用户)。

Or another solution: 或其他解决方案:

Change your date1 field to a string. 将您的date1字段更改为字符串。 If your date is not correct, send the original value back to your page. 如果您的日期不正确,请将原始值发送回您的页面。

DateTime date;

if (DateTime.TryParse(date1, out temp))    
{
    //The date is fine, save it.
}
else
{
    ModelState.AddError("date1", "Incorrect date: " + date1);
}

Then in your editor you just display a normal text field, don't need to make a conversion. 然后,在您的编辑器中,您只需显示一个普通的文本字段,无需进行转换。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM