我们有一个名为 DateReleased 的属性,为其添加了以下数据注释属性
[Required]
[DataType(DataType.Date, ErrorMessage = "Please enter date")]
[DisplayName("Date Released")]
public object DateReleased { get; set; }
下面是向数据库中插入一条新记录的操作
[HttpPost]
public ActionResult Create([Bind(Exclude="Id")] Movie movie)
{
try
{
if (ModelState.IsValid)
{
_entities.AddToMovies(movie);
_entities.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}
catch
{
return View();
}
}
我通过在创建 View 中放置以下代码行来启用客户端验证
<script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcValidation.js"></script>
<% Html.EnableClientValidation(); %>
但我很惊讶地发现只有 Required 验证在客户端触发。 Date 的数据类型验证仅在服务器端触发。请让我知道客户端验证失败的原因以及触发客户端验证的解决方法。
最佳答案
是的。如下添加自定义属性类
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class DateAttribute : DataTypeAttribute
{
public DateAttribute() : base(DataType.Date) { }
public override string FormatErrorMessage(string name)
{
if (ErrorMessage == null && ErrorMessageResourceName == null)
{
ErrorMessage = ValidatorResources.DateAttribute_Invalid;
}
return base.FormatErrorMessage(name);
}
public override bool IsValid(object value)
{
if (value == null) return true;
DateTime retDate;
return DateTime.TryParse(Convert.ToString(value), out retDate);
}
}
创建客户端验证规则类
public class ModelClientValidationDateRule:ModelClientValidationRule
{
public ModelClientValidationDateRule(string errorMessage)
{
ErrorMessage = errorMessage;
ValidationType = "date";
}
}
创建一个适配器类,它与自定义属性和客户端验证规则 Hook ,如下所示。确保添加上述属性类的引用
public class DateAttributeAdapter : DataAnnotationsModelValidator<DateAttribute>
{
public DateAttributeAdapter(ModelMetadata metadata, ControllerContext context, DateAttribute attribute)
: base(metadata, context, attribute) { }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationDateRule(ErrorMessage) };
}
}
然后修改global.asax文件
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DateAttribute), typeof(DateAttributeAdapter));
}
如下所示将属性添加到模型类
[Date]
public object DateReleased { get; set; }
在 View 中添加以下客户端代码
<script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcValidation.js"></script>
<script type="text/javascript">
Sys.Mvc.ValidatorRegistry.validators["date"] = function (rule) {
// initialization code can go here.
return function (value, context) {
if (value.length > 0) {
var d = new Date(value);
if (!isNaN(d))
return true;
return rule.ErrorMessage;
}
else {
return true;
}
};
};
希望对您有所帮助。
关于asp.net-mvc - 数据类型客户端验证在 MVC 2 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222831/