mvc 5 验证过去的日期

Mao*_*lay 3 html c# asp.net asp.net-mvc asp.net-mvc-5

我在这里看到了问题,但无法解决问题。

我希望当用户在表单中插入日期时,只有过去的日期才是相关的。

例子:

用户无法插入 2016 年 2 月 3 日之后的日期。

我的型号:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
[Required(ErrorMessage = "Date is mandatory")]
public DateTime created_date { get; set; }
Run Code Online (Sandbox Code Playgroud)

我的看法:

<div class="form-group" >
    @Html.LabelFor(model => model.created_date, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10" >
        @Html.EditorFor(model => model.created_date, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.created_date, "", new { @class = "text-danger" })
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

谢谢。

Dar*_*ren 6

您可以使用HTML 5日期类型,例如:

<input type="date" max="2016-03-02">
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/nsvno84t/1/

要使用 Razor 执行此操作,它将为您提供今天的日期:

<input type="date" max='@DateTime.Now.ToString("dd/MM/yyyy")'>
Run Code Online (Sandbox Code Playgroud)

但是,您可能想要确定用户/服务器日期时间设置,因为这适用于英国格式(@DateTime.Now.ToString("yyyy-MM-dd")在您的情况下,类似的设置可能更好)。

您还应该针对服务器和客户端验证它,在您的 MVC 代码中您可以使用ValidationAttribute.

public class RestrictedDate : ValidationAttribute
{
   public override bool IsValid(object date) 
   {
       DateTime date = (DateTime)date;
       return date < DateTime.Now;
   }
}
Run Code Online (Sandbox Code Playgroud)

RestrictedDate然后在模型上使用新属性:

public class YourModel
{
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date")]
    [Required(ErrorMessage = "Date is mandatory")]
    [RestrictedDate]
    public DateTime created_date { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

作为补充说明,您可能还需要考虑更改created_dateCreatedDate以符合C#命名约定。