I use MVC 3 in C#, I have a class with this Attribute
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}", ApplyFormatInEditMode = true)]
I would like to enforce Validation when a User is in EDIT MODE
Data in database is stored with type datetime formatted like this
6/15/2009 1:45:30 PM
I receive this error
Error String is not in correct format
I believe the problem is in
DataFormatString = "{0:dd MMM yyyy}"
any idea how to fix it?
The
DisplayFormatattribute is literally only for displaying the value. If you set theApplyFormatInEditModeall it will do is also apply the format to the contents of your data when displayed in a textbox (intended for Editing). It’s got nothing to do with validation.If you want to validate the input using the format you’ve specified you’ll likely have to create your own
ValidationAttribute, and useDateTime.ParseExact()to attempt to ensure it meets the format you’re expecting. The only draw back is it will not have an accompanying client side validation logic unless you write it.I have not tested this thuroughly, but it should give you a start.
Then it’s just a matter of using it.
[DateTimeFormat(Format = "dd MMM yyyy")]UPDATE: Sorry I donn’t think I clearly read your question. The reason it’s complaining about the data on postback is because the format you’re trying to use is not a standard one. You might be better off implementing one of the common date pickers online to use when populating the field rather than letting it be hand edited or expecting a non-standard format like this. Custom display formats are great for displaying, but if you want to use a custom format for edit mode that the default
DateTime.Parsedoesn’t understand you’d have to write your own ModelBinder I believe, and that’s something I’d not done, alternatively you could change the data type on your viewmodel to string and the parse it yourself in the action method (you could still use the validator I provided in this case). To get rid of your error (but will also remove your custom format when in edit mode) you’d have to remove theApplyFormatInEditModeproperty.