Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 .

like image 560
Jitender Kumar Avatar asked Mar 27 '26 17:03

Jitender Kumar


1 Answers

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; }
like image 132
Zafar Avatar answered Mar 29 '26 05:03

Zafar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!