1

I have this code:

@Html.TextBoxFor(m => Model.MyDateTime)

MyDateTime - is DateTime object. It shows correct date and time inside textbox: 09/10/2010 05:19:56 PM But when I try to click submit button it shows that it is incorrect value. I use jquery.validate.unobtrusive.js file for validation.

Sergey
  • 7,933
  • 16
  • 49
  • 77
  • What is the manner in which you are setting up validation for the `MyDateTime` property? – moribvndvs Dec 20 '12 at 21:13
  • I have [asked about the same thing in the past](http://stackoverflow.com/questions/12930640/in-asp-net-mvc-4-how-to-validate-that-a-datetime-value-is-entered-on-the-correc). See the accepted answer there. – aknuds1 Dec 20 '12 at 22:56

3 Answers3

2

The gist of the solution I pointed to in my comment is that you can use a specialized model for the view which contains a string representation instead of the DateTime type, which allows you to easily validate the value with RegularExpressionAttribute. When you receive this model on the server (as posted from the client), simply convert it to a corresponding database model.

public class ViewModel
{
    [Required]
    [RegularExpression("\d{2}-\d{2}-\d{4}\s\d{2}:\d{2}:\d{2}")]
    public string MyDateTime { get; set; }

    public Model ToPoco()
    {
        return new Model {
            MyDateTime = DateTime.Parse(this.MyDateTime, "MM-dd-yyyy H:mm:ss")
        };
    }
}

public class Model
{
    DateTime MyDateTime { get; set; }
}
aknuds1
  • 65,625
  • 67
  • 195
  • 317
1

data annotation will work for you!

0

You could use dataannotaion for validate yor model field properly. Using such annatation you could manualy prvide format of date in your annotation passing string pattern to it. And in that case it will perefectly working with default mvc validation.

Ph0en1x
  • 9,943
  • 8
  • 48
  • 97