Validate textbox to accept only valid datetime value using DataAnnotations in mvc3

10,016

1. Your client side validation is not working. You are seeing error message after the form is submitted - means client side validation is not working properly. To make the client side validation work, ASP.NET MVC assumes that you have jquery.validate.js and jquery.validate.unobtrusive.js referenced on the page. You can download them using NuGet Package Manager on your Visual Studio.

2. Date field is not being validated. You are expecting the DisplayFormat to validate the date format for you. But actually it does not. That is more of about displaying your date on the View.

In order to validate the date format, you need to use your own custom Attribute. Or you can simply use RegularExpression attribute. The most simple example looks like this:

[RegularExpression(@"\d{1,2}/\d{1,2}/\d{2,4}\s\d{1,2}:\d{1,2}", ErrorMessage = "")]

Or if you want to make a custom attribute, then:

public class DateFormatValidation : ValidationAttribute{
    protected override bool IsValid(object value){
        DateTime date;
        var format = "0:dd/MM/yyyy HH:mm"
        bool parsed = DateTime.TryParseExact((string)value, format, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out date)
        if(!parsed)
            return false;
        return true;
    } 
}

Then use it like:

[DataType(DataType.DateTime, ErrorMessage = "Invalid Datetime")]
[DateFormatValidation]
[Display(Name = "Start Datetime")]
public DateTime? StartDateTime { get; set; }
Share:
10,016
Jitender Kumar
Author by

Jitender Kumar

Updated on July 14, 2022

Comments

  • Jitender Kumar
    Jitender Kumar almost 2 years

    I want to validate a textbox to accept datetime value using DataAnnotations in MVC3. But I don't have any idea how to do it. Given below is what I'm trying to accomplish my requirement and it's not working.

        [DataType(DataType.DateTime, ErrorMessage = "Invalid Datetime")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
        [Display(Name = "Start Datetime")]
        public DateTime? StartDateTime { get; set; }
    

    As When I click on submit button after filling corrupted data first problem is that form get post and later it shows the message that "Invalid date" and second if I enter just date without time still form get post but this time it does not shows the message which is also wrong.

    So I just want to know how can I validate my textbox to accept datetime in "dd/MM/yyyy HH:mm" format only using MVC DataAnnotations .