I am checking a datetime field in mvc view for datetime format like this:
If contactToValidate.LastUpdated = Nothing OrElse Not IsDate(contactToValidate.LastUpdated) OrElse CType(contactToValidate.LastUpdated, DateTime) = DateTime.MinValue Then
_validationDictionary.AddError("AddErrorValue", "Date Format is not Correct!")
End If
but , if the input for LastUpdated in View , left blank, beside my own error ("Date Format is not Correct!") , the default error message is shown: A value is required. I believe this is what mvc framework automatically checked for datatype conversions, but as I'm checking the LastUpdated textbox for null and datetime format, I dont want this error message to be shown. I just want my own. How can I do that? Thanks
You are probably getting this message because the date field is being bound to a non-nullable DateTime on your presentation model. If you change the type of that field or property to a nullable DateTime, you should no longer get this message.
In any event, you can customize the message that the user sees by implementing IDataErrorInfo on your presentation model.
I ran into this issue too - it does indeed seem to occur where a model field is bound to a non-nullable type on your data model.
The way I've bypassed this is to clear down the error information in the ModelState. In my exception handler on my controller method, I do this:
foreach (var state in ModelState.Values)
{
if (state.Errors.Count > 0)
state.Errors.Clear();
}
which removes the default validation behaviour, then runs my own. Note that doing this will leave you with errors but no description if your own validation doesn't cover all of your fields. If it is only a single field that you want to clear however, you can check for its name in the ModelState dictionary, and just clear that one.
It's unfortunate that no matter where you look, most of the answers to this question are "Implement IDataErrorInfo!".
This same problem shows up if you try to, for example, type a text string into a textbox field bound to an integer property. Simply, if MVC cannot convert the user value to the proper type, it generages these (quite useless) generic errors and never calls upon the IDataErrorInfo members.
It's definately a hassle to override these unhelpful messages, and personally I feel the best answer is to simply implement some client-side validation to handle these scenarios. The cases where it generates these messages are very consistent and easily predictable:
Plus, client side validation is just good practice anyways. If the user doesnt have javascript enabled then they'll certainly be able to figure out the problem anyways if you're using Html.ValidationMessage() and / or styling the input fields to identify the problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With