Reputation: 6997
I have:
public class StudentDto
{
[Display(Name = "Data de Nascimento")]
public DateTime? Born { get; set; }
}
I'm using jQuery datepicker
, and whenever I put an invalid data, the validation message is: Please enter a valid date.
How can i change this default message?
I've already tried using:
[DataType(DataType.Date, ErrorMessage = @"Valor inválido")]
I've already tried to create a .resx
, and use DefaultModelBinder.ResourceClassKey = "Strings";
, and on my .resx
created values for: InvalidPropertyValue
, Common_ValueNotValidForProperty
, PropertyValueInvalid
None of these worked.
Thanks!
Upvotes: 3
Views: 4691
Reputation: 1672
Use DefaultModelBinder.ResourceClassKey = "Strings";
for binding validation (forums.asp.net/post/3607981.aspx) and ClientDataTypeModelValidatorProvider.ResourceClassKey = "Strings";
for unobtrusive validation.
Strings
- name of resource file located in App_GlobalResources
folder (~/App_GlobalResources/Strings.resx
).
Upvotes: 1
Reputation: 1038720
The following works fine for me:
Model:
public class StudentDto
{
[Display(Name = "Data de Nascimento")]
[Required(ErrorMessage = "Some custom message for required date")]
public DateTime? Born { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new StudentDto());
}
[HttpPost]
public ActionResult Index(StudentDto dto)
{
return View(dto);
}
}
View:
<script type="text/javascript">
$(function () {
$('#Born').datepicker();
});
</script>
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Born)
@Html.EditorFor(x => x.Born)
@Html.ValidationMessageFor(x => x.Born)
<button type="submit">OK</button>
}
Application_Start
in Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
DefaultModelBinder.ResourceClassKey = "Strings";
}
and inside ~/App_GlobalResources/Strings.resx
define the key PropertyValueInvalid
which will be used if an invalid date is entered. For the value you could use the {0}
and {1}
placeholders which will be replaced respectively by the value and the display name of the field.
Upvotes: 3