我有一个 ASP.NET MVC 4 应用程序,我想对视图模型的几个属性进行不显眼的验证。这是一个简化版本:
视图模型:
[AtLeastOne(new[] {"FirstName", "LastName"})]
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
验证属性:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AtLeastOneAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _propertyNames;
public AtLeastOneAttribute(string[] propertyNames)
{
if (propertyNames == null) throw new ArgumentNullException("propertyNames");
if (propertyNames.Length < 2) throw new ArgumentOutOfRangeException("propertyNames");
_propertyNames = propertyNames;
}
public override bool IsValid(object value)
{
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ErrorMessage = "AAAAA!!!",
ValidationType = "atleastone",
};
modelClientValidationRule.ValidationParameters.Add(new KeyValuePair<string, object>("propertynames", _propertyNames));
return new[]
{
modelClientValidationRule
};
}
}
虽然我有:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
在 Web.config 和
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add("atleastone", ['FirstName', 'LastName'], function (options) {
alert('options!');
});
</script>
在我看来,此验证不会呈现任何内容。例如,如果我为 FirstName 或 LastName 添加 [Required],则会添加 data-* 验证属性。
如何实现这种多属性自定义客户端验证?
想查看/下载整个解决方案吗?