验证日期格式MVC中 [英] Validate DateFormat In Mvc

查看:151
本文介绍了验证日期格式MVC中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属性ExpiredDate MVC中定义

I have a property ExpiredDate define in MVC

[Required]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime? ExpirationDate { get; set; }

我想验证,如果一个页面上的日期是不正确的格式。
我使用日期的格式的 MM / DD / YYYY

推荐答案

您应该包括<一个href=\"https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.datatypeattribute(v=vs.110).aspx\"相对=nofollow> 数据类型 与<一个属性href=\"https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.datatype(v=vs.110).aspx\"相对=nofollow> DataType.Date 。这些都可以在 <找到code> System.ComponentModel.DataAnnotations 命名空间。

You should include the DataType attribute with DataType.Date. These can both be found in the System.ComponentModel.DataAnnotations namespace.

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? ExpirationDate { get; set; }

<一个href=\"http://stackoverflow.com/questions/12109007/unable-to-set-datetime-format-in-mvc-4-using-data-annotations\">This回答还包括一些更多的属性。

This answer also includes some more attributes.

更新以包括指示启用ASP.NET MVC4客户端验证

Updated to include instructions to enable client-side validation in ASP.NET MVC4

要启用客户端验证,你需要这样的:

To enable client-side validation, you need to this:


  1. 添加jquery.validation插件页脚

  1. Add the jquery.validation plugin to the footer

<%: Scripts.Render("~/Scripts/jquery.validate.min.js") %>
<%: Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") %>


  • 这添加到web.config文件

  • Add this to web.config

    <appSettings>
      <add key="ClientValidationEnabled" value="true" />
      <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    


  • 当使用@ Html.ValidationMessageFor()
  • 使用这个CSS,使其initally隐藏,并通过JavaScript验证显示

  • Use this css when using @Html.ValidationMessageFor() so that it is initally hidden and displays via the javascript validation

    <style type="text/css">
    
    /* styles for validation helpers */
    .field-validation-error {
        color: #e80c20;
        font-weight: bold;
    }
    
    .field-validation-valid {
        display: none;
    }
    
    input.input-validation-error {
        border: 1px solid #e80c20;
    }
    
    input[type="checkbox"].input-validation-error {
        border: 0 none;
    }
    
    .validation-summary-errors {
        color: #e80c20;
        font-weight: bold;
        font-size: 1.1em;
    }
    
    .validation-summary-valid {
        display: none;
    }
    
    </style>
    


  • 这篇关于验证日期格式MVC中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆