自定义验证规则
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace mvctest { public static class MVCHellper { public static string GetErrors(ModelStateDictionary ms) { System.Text.StringBuilder sbtext = new System.Text.StringBuilder(); foreach (var item in ms.Keys) { if (ms[item].Errors.Count <= 0) { continue; } sbtext.Append("错误消息为:"); foreach (var itemerror in ms[item].Errors) { sbtext.Append(itemerror.ErrorMessage + "<br/>"); } } return sbtext.ToString(); } } /// <summary> /// 第一种 /// </summary> public class PhoneAttribute : RegularExpressionAttribute { public PhoneAttribute() : base(@"^(?:\+?86)?1(?:3\d{3}|5[^4\D]\d{2}|8\d{3}|7(?:[35678]\d{2}|4(?:0\d|1[0-2]|9\d))|9[189]\d{2}|66\d{2})\d{6}$") { this.ErrorMessage = "手机号不正确"; } } /// <summary> /// 第二种 /// </summary> public class chinaPhoneAttribute : ValidationAttribute { public chinaPhoneAttribute() { this.ErrorMessage="错误"; } public override bool IsValid(object value) { if (value is string) { string s = (string)value; if (s.StartsWith("13")) { return true; } else { return false; } } else { return false; } //return base.IsValid(value); } } }