[英]MVC Unobtrusive Client-side validation not firing
I would like to implement client-side validation in ASP.NET MVC 4. After implementing the IClientValidatable interface and adding the adapter and client validation code, the validation is still not working. 我想在ASP.NET MVC 4中实现客户端验证。在实现IClientValidatable接口并添加了适配器和客户端验证代码之后,验证仍然无法进行。 Please see the code below: Custom Validation Attribute:
请参见以下代码:自定义验证属性:
namespace MvcApplication1.Models
{
[AttributeUsage(AttributeTargets.Property)]
public class DateLessThanCurrentAttribute:ValidationAttribute,IClientValidatable
{
public DateLessThanCurrentAttribute(string errorMessage)
:base(errorMessage)
{ }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
ValidationResult validationResult = ValidationResult.Success;
if((DateTime)value>=DateTime.Now)
{
validationResult = new ValidationResult(FormatErrorMessage(base.ErrorMessage));
}
return validationResult;
}
#region IClientValidatable Implementation
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
string errorMessage = base.ErrorMessage;
ModelClientValidationRule dateLessthanCurrentValidationRule = new ModelClientValidationRule();
dateLessthanCurrentValidationRule.ErrorMessage = FormatErrorMessage(errorMessage);
dateLessthanCurrentValidationRule.ValidationType = "datelessthancurrent";
yield return dateLessthanCurrentValidationRule;
}
#endregion
}
}
Razor View: 剃刀视图:
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
@Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/Custom/CustomValidation.js"></script>
}
Adapter and Validator: 适配器和验证器:
/// <reference path="jquery.validate.js"/>
/// <reference path="jquery.validate.unobtrusive.js"/>
$.validator.unobtrusive.adapters.addBool("datelessthancurrent");
$.validator.addMethod("datelessthancurrent", function (value, element,params) {
alert('hey you!!!');
return false;
});
Oh, i found the problem. 哦,我发现了问题。 The redundant lines below were the cause.
原因如下。 Removing these lines solves the problem.
删除这些行即可解决问题。
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.