Organizational Research By

Surprising Reserch Topic

validate a date in a specific format in asp net mvc 3


validate a date in a specific format in asp net mvc 3  using -'asp.net,asp.net-mvc,validation,asp.net-mvc-3'

I have a property of type DateTime MyDate in my ViewModel. I want to make sure that the user only enters the Date part in a text box in a specific format (dd.mm.yyyy) and tried the following attributes:

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode=true)]
[RegularExpression(@"^(([0-2]\d|[3][0-1])\.([0]\d|[1][0-2])\.[2][0]\d{2})$",
    ErrorMessage="Failed...")]
public DateTime MyDate { get; set; }


The controller action signature for a HttpPost looks like this:

[HttpPost]
public ActionResult Edit(int id, MyViewModel viewModel)
{
    // MyViewModel contains the MyDate property ...
    // ...
    if (ModelState.IsValid)
    {
        // ...
    }
    // ...
}


In the Razor view I tried the following two ways:


@Html.TextBoxFor(model => model.MyDate)
@Html.EditorFor(model => model.MyDate)


It doesn't work as I want. The result is:


Client side validation works as expected with both Html helpers
Server side validation always fails for both helpers, even with valid dates like "17.06.2011" which pass the regular expression. The MyDate property is filled correctly with the entered date in viewModel which is passed to the action. So it seems that model binding was working.
The DisplayFormat attribute is only respected by EditorFor but not by TextBoxFor. TextBoxFor displays "dd.mm.yyyy hh:mm:ss"


Questions:


Can I apply a RegularExpressionAttribute at all on a property which isn't a string? If it is allowed how is the reg ex evaluated for a non-string property like DateTime on server side? Is something like MyDate.ToString() compared with the reg ex? (It would explain that the validation fails because ToString will return a string including time part which doesn't pass the regular expression.)
Is the DisplayFormat attribute generally only respected by EditorFor and never by TextBoxFor?
How can I do a date validation right?

    

asked Oct 7, 2015 by sandeep bhadauria
0 votes
10 views



Related Hot Questions

2 Answers

0 votes

Don't use regular expressions to validate dates, they are simply ignored.

Differences in cultures might be the root of your problem. Client side validation uses the browser's culture in order to validate the date. So for example if it is configured to en-US the expected format would be MM/dd/yyyy. If your server is configured to use fr-FR the expected format would be dd/MM/yyyy.

You could use the element in web.config to set the server side culture. You could configure it in such a way that it uses the same culture as the client:


Hanselman has a nice blog post about globalization and localization in ASP.NET MVC.

answered Oct 7, 2015 by tejas lakhani
0 votes

I have now thrown away the RegularExpression. It doesn't seem to be suited on a property of type DateTime. Then I created a new validation attribute for DateTime and nullable DateTime:

[AttributeUsage(AttributeTargets.Property, Inherited = false,
    AllowMultiple = false)]
public sealed class DateOnlyAttribute : ValidationAttribute
{
    public DateOnlyAttribute() :
        base("\"{0}\" must be a date without time portion.")
    {
    }

    public override bool IsValid(object value)
    {
        if (value != null)
        {
            if (value.GetType() == typeof(DateTime))
            {
                DateTime dateTime = (DateTime)value;
                return dateTime.TimeOfDay == TimeSpan.Zero;
            }
            else if (value.GetType() == typeof(Nullable))
            {
                DateTime? dateTime = (DateTime?)value;
                return !dateTime.HasValue
                    || dateTime.Value.TimeOfDay == TimeSpan.Zero;
            }
        }
        return true;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(CultureInfo.CurrentCulture,
            ErrorMessageString, name);
    }
}

Usage:

[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode=true)]
[DateOnly]
public DateTime MyDate { get; set; }

It doesn't provide client side validation. On server side the validation relies on model binding (to make sure that the entered string is convertable to a DateTime at all). If the user entered a time part other than midnight the DateOnly attribute kicks in and she gets a warning that only a date should be entered.

answered Oct 7, 2015 by patelnikul321

...