MVC Unobtrusive客户端验证未触发

时间:2014-11-12 21:58:30

标签: jquery model-view-controller unobtrusive-javascript

我想在ASP.NET MVC 4中实现客户端验证。在实现IClientValidatable接口并添加适配器和客户端验证代码之后,验证仍然无效。请参阅以下代码: 自定义验证属性:

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查看:

<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>
}

适配器和验证器:

/// <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;
});

1 个答案:

答案 0 :(得分:0)

哦,我发现了问题。下面的冗余线是原因。删除这些行可以解决问题。

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>