自定义mvc验证特性,手机号号段老增加,给自定义一个RegularExpress

时间:2022-01-05 08:03:10

public class PhoneExpressionAttribute: RegularExpressionAttribute, IClientValidatable
{
public PhoneExpressionAttribute()
: base(@"^1[2,3,4,5,6,7,8,9][0-9]{1}[0-9]{8}$")
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,"手机号码不正确",name);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var name = metadata.GetDisplayName();
var rule = new ModelClientValidationRegexRule(FormatErrorMessage(name), Pattern);
yield return rule;
}
}

引用
[PhoneExpression]
public string Mobile { get; set; }