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.

2

3 Answers 3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.