该DisplayFormat
属性实际上仅用于显示值。如果您设置ApplyFormatInEditMode
它,它还将在文本框中显示时将格式应用于数据内容(用于编辑)。它与验证无关。
If you want to validate the input using the format you've specified you'll likely have to create your own ValidationAttribute
, and use DateTime.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.
public class DateTimeFormatAttribute : ValidationAttribute
{
public int Format { get; set; }
public override bool IsValid(object value)
{
if (value == null)
return true;
DateTime val;
try
{
val = DateTime.ParseExact(value.ToString(), Format, null);
}
catch(FormatException)
{
return false;
}
//Not entirely sure it'd ever reach this, but I need a return statement in all codepaths
return val != DateTime.MinValue;
}
}
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.Parse
doesn'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 the ApplyFormatInEditMode
property.