16

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.

5
  • 3
    MVC will validate according to formate by default, if you need client side validation, you need to turn on unobtrusive javascript on you application Commented May 15, 2013 at 12:57
  • Set the ApplyFormatInEditMode property to true in the DisplayFormatAttribute Commented May 15, 2013 at 13:03
  • @asawyer Sir it doesnot validate and page postback. i want to stop the postback and want to show the format message. Commented May 15, 2013 at 13:12
  • 1
    Please also read the first comment: You need to turn on unobtrusive javascript on your application Commented May 15, 2013 at 13:14
  • @ Kenneth how to do that. Commented May 15, 2013 at 13:32

3 Answers 3

26

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;
    }
    
Sign up to request clarification or add additional context in comments.

6 Comments

To enable client-side validation, just add the jquery.validate plugin to your footer like this: <%: Scripts.Render("~/Scripts/jquery.validate.min.js") %> <%:Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js") %>
Sir @truemedia, i have tried this code [Required(ErrorMessage="ss")] [DataType(DataType.Date)] [DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")] public DateTime? date { get; set; }
the page still postback even if it doesnt contain any date and also postback when i put a simple integer 345
Did you add the client-side validation javascript files to the view? Those two javascript files (jquery.validate.min.js and jquery.validate.unobtrusive.min.js) should be included in the MVC default project template.
Thanks sir, but by using [RegularExpression(@"^(([0-2]\d|[3][0-1])\.([0]\d|[1][0-2])\.[2][0]\d{2})$",ErrorMessage = "End Date should be in MM/dd/yyyy format")] it works for me
|
13

Custom validation date format must be solved manually.

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. It is not caused by datepicker nor browsers. Unfortunately you have to solve it manually.

My finally working solution:

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

And then you can finally add fix for date format parser:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

1 Comment

for example in ... <head> <script> .. here </script> </head> ...
-5

You can use validation like:

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

I think it will work

1 Comment

No sir page postback if i type 12345 and submit the form or any invalid date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.