2016-03-02 49 views
2

我在这里看到了问题,但我无法解决问题。mvc 5验证过去的日期

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

例如:

用户不能在02/03/2016后插入日期。

我的模型:

[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; } 

我的观点:

<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> 

感谢。

+0

附注:既然你似乎想要HTML5的浏览器日期选择器(这仅适用于Chrome和边缘支持) ,格式必须是'DataFormat String =“{0:yyyy-MM-dd}”'为了正常工作。您应该考虑使用自定义验证属性来获取客户端和服务器端验证。 –

回答

2

可以使用HTML 5日期类型,作为一个例子:

<input type="date" max="2016-03-02"> 

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

要使用剃刀做到这一点,这将给你今天的日期:

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

然而,你可能想要确定用户/服务器的日期时间设置,因为这将适用于英国格式(类似@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; 
    } 
} 

然后使用你的模型新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; } 
} 

作为附加的注释,你可能还需要考虑改变created_dateCreatedDate符合C#命名约定。

+0

我在模型中写这个类?或在模型文件夹中?并且在这一行中有错误DateTime date =(DateTime)date; –

+0

为什么我不能提及@Darren Davies? –

+0

你能帮我吗@Darren Davies? –

0

我会建议在控制器中使用条件语句进行验证。我不知道,如果你在你的CreateEdit视图,但在你的控制器,你可以验证这样的:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Include = "ID, created_date" /* and whatever else you have in your model*/)] YourModel yourModel) 

if(ModelState.IsValid) 
{ 
    if (yourModel.created_date > DateTime.Today) 
    { 
     ModelState.AddModelError("created_date", "Date cannot be set to future date!"); 
     return View(yourModel); 
    } 

    return View(yourModel); 
} 

但这种情况正在验证对服务器..所以我也建议该验证相结合的客户端验证@Darren Davies在他的回答中给出的..

0

第一你必须改变

[DisplayFormat(DataFormatString = “{0:DD-MM-YYYY}”,ApplyFormatInEditMode =真)]

到 [DisplayFormat(DataFormatString =“{0: YYYY-MM-DD}”,ApplyFormatInEditMode =真)]

怎么一回事,因为一些浏览器不给完美的结果

+0

感谢您的提示 –

+0

欢迎,但更好地使用jquery datepicker –

+0

你可以向我解释?我使用jquery –