Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate DateFormat In Mvc

I have a property ExpiredDate define in MVC

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

I want to Validate if Date on a page is not in correct format. The format of date I am using is MM/dd/yyyy.

like image 563
Abhishek Avatar asked May 15 '13 12:05

Abhishek


1 Answers

You should use the DataType attribute with DataType.Date. Both of which are in the System.ComponentModel.DataAnnotations namespace and can be used like this:

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

This answer also includes some more attributes.

Update: To enable client-side validation in ASP.NET MVC4, you need to do this:

  1. Add the jquery.validation plugin to the footer

    <%: Scripts.Render("~/Scripts/jquery.validate.min.js") %>
    <%: Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") %>
    
  2. Add this to web.config

    <appSettings>
      <add key="ClientValidationEnabled" value="true" />
      <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    
  3. Use this css when using @Html.ValidationMessageFor() so that it is initially hidden and displays via the javascript validation

    /* 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;
    }
    
like image 68
truemedia Avatar answered Sep 19 '22 04:09

truemedia