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

安稳与你 提交于 2019-12-11 01:54:56

问题


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 .


回答1:


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; }



回答2:


I got it from diff website, saying its a problem in chrome and he has fixed it by applying this code. So check first if it works in firefox then you might be forced to apply this code, however this code skips checking the date format.

$.validator.methods["date"] = function (value, element) { return true; }


来源:https://stackoverflow.com/questions/21724449/validate-textbox-to-accept-only-valid-datetime-value-using-dataannotations-in-mv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!