MVC 不显眼的客户端验证未触发

MVC Unobtrusive Client-side validation not firing

提问人:arlvin 提问时间:11/13/2014 更新时间:11/17/2014 访问量:2542

问:

我想在 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
}
}

剃刀视图:

<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;
});
jquery model-view-controller unobtrusive-javascript

评论


答:

1赞 arlvin 11/17/2014 #1

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

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