MVC 默认不提供依赖验证规则,为了达到依赖验证的目的,需要我们自定义验证规则,并实现相关方法。添加依赖验证需要做到以下几步
- 新建验证规则特性类并实现相关接口
- 添加前端验证js
- 给需要验证的属性添加验证规则
下面以证件类型配合证件号码验证具体实现
首先新建 IdCardAttribute验证规则类继承ValidationAttribute基类, 并实现IClientValidatable接口具体实现代码如下
//指定验证规则适用范围为属性
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class IdCardAttribute : ValidationAttribute, IClientValidatable
{
//依赖项名称属性
public string OtherPropertyName { get; private set; }
public IdCardAttribute(string otherPropertyName)
{
this.OtherPropertyName = otherPropertyName;
}
//实现具体验证逻辑
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var result = ValidationResult.Success;
//获取依赖项值,本例中为证件类型 1为身份证进行验证 其他不做验证
var otherValue = validationContext.ObjectType.GetProperty(OtherPropertyName).GetValue(validationContext.ObjectInstance, null);
if (otherValue == null)
{
otherValue = "1";
}
if (value != null && otherValue.ToString() == "1")
{
//简单的身份证验证
string regstr = @"(^d{15}$)|(^d{18}$)|(^d{17}(d|X|x)$)";
Regex regex = new Regex(regstr);
if (!regex.IsMatch(value.ToString()))
{
result = new ValidationResult(ErrorMessage);
}
}
return result;
}
//返回该类的客户端验证规则
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "idcard"
};
rule.ValidationParameters["otherpropertyname"] = OtherPropertyName;
yield return rule;
}
}
上面是实现后台相关逻辑,要实现前端页面js验证还需要对jquery 验证规则进行扩展,代码如下
jQuery.validator.unobtrusive.adapters.add('idcard', ['otherpropertyname'],
function (options) {
options.rules['idcard'] = options.params;
if (options.message) {
options.messages['idcard'] = options.message;
}
}
);
jQuery.validator.addMethod('idcard', function (value, element, params) {
var otherFieldValue = $('input[name="' + params.otherpropertyname +'"]').val();
if (otherFieldValue == 1 && value) {
var tel = /(^d{15}$)|(^d{18}$)|(^d{17}(d|X|x)$)/;
return tel.test(value);
}
customValidation.addDependatControlValidaitonHandler(element,params.otherpropertyname);
return true;
}, '');
至此相关代码已经编写完成,使用时类似MVC默认提供的验证规则
属性标记
/// <summary>
/// 证件类型
/// </summary>
public String CardType
{
get;set;
}
/// <summary>
/// 证件号码
/// </summary>
[Required(ErrorMessage = "证件号码不能为空")]
[IdCard("CardType", ErrorMessage = "请输入正确的证件号码")]
public String CardNo
前台html标记
<div class="row">
<div class="col-xs-12 col-sm-2 col-md-2 text_label">证件类型:</div>
<div class="col-xs-12 col-sm-4 col-md-4">
@Html.DropDownListFor(a => a.CardType, new SelectList(new List<dynamic>() { new { id = "1", name = "身份证" }, new { id = "2", name = "其他" } }, "id", "name"), new { Class = "col-xs-7" })
</div>
<div class="col-xs-12 col-sm-2 col-md-2 text_label">证件号码:</div>
<div class="col-xs-12 col-sm-4 col-md-4">
@Html.TextBoxFor(a => a.CardNo)
<span class="requiredstar">*</span>
@Html.ValidationMessageFor(a => a.CardNo)
</div>
</div>
至此MVC依赖验证基本完成,这里虽然只是以一个简单的验证规则为例,相信碰到复杂的按照这个原理一步步来也不在话下。