问题描述:ASP.Net Core中本地化日期格式验证无效。
解决方法:
public void ConfigureServices(IServiceCollection services)
{
// 添加本地化支持
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("zh-CN")
};
options.DefaultRequestCulture = new RequestCulture("zh-CN");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
services.AddMvc()
.AddViewLocalization()
.AddDataAnnotationsLocalization();
}
[DataType(DataType.Date)]
属性进行日期类型字段的验证,同时使用[DisplayFormat]
属性指定日期的格式。public class MyModel
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime MyDate { get; set; }
}
@Html.EditorFor
或@Html.TextBoxFor
来生成日期输入框,并使用asp-format
属性指定日期的格式。@model MyModel
@Html.LabelFor(m => m.MyDate)
@Html.EditorFor(m => m.MyDate, new { htmlAttributes = new { @class = "form-control", asp_format = "{0:yyyy-MM-dd}" } })
@Html.ValidationMessageFor(m => m.MyDate)
@Html.ValidationSummary
来显示日期验证的错误信息。@Html.ValidationSummary(true, "", new { @class = "text-danger" })
这样就可以正确地进行本地化日期格式的验证了。