.Net MVC Validation 驗證Model
阿新 • • 發佈:2018-12-25
1.手動驗證指定Model
只能單個Model 驗證
using System.ComponentModel.DataAnnotations;
var ArrValidation = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(ArrCusBusInfo[0], new ValidationContext(ArrCusBusInfo[0]), ArrValidation, true);
2.自定義驗證 繼承ValidationAttribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class MyValidAttribute : ValidationAttribute { public IEnumerable<string> Values { get; private set; } public MyValidAttribute(string value) { this.Values = new string[] { value }; } public MyValidAttribute(prams string[] values) { this.Values = values; } public override bool IsValid(object value) { if (null == value) { return true; } return this.Values.Any(item => value.ToString() == item); } public override string FormatErrorMessage(string name) { string[] values = this.Values.Select(value => string.Format("'{0}'",value)).ToArray(); return string.Format(base.ErrorMessageString, name,string.Join(",", values)); } } CusBusInfo.cs [DisplayName("性別")] [MyValid("M", "F", "m", "f", ErrorMessage = "性別只能是M/F")] public string Gender { get; set; }
3.Controller手動驗證
ModelState.Remove("BSA");//去除某些欄位驗證
ModelState.AddModelError("Gender", "'性別只能是M/F");//手動增加驗證錯誤
4.讓資料型別實現IValidatableObject介面
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { CusBusInfo OCusBusInfo = validationContext.ObjectInstance as CusBusInfo; if (string.IsNullOrEmpty(OCusBusInfo.Gender)) { yield return new ValidationResult("'Gender'是必需欄位", new string[] { "Gender" }); } else if (!new string[]{"M","F"}.Any(g=>string.Compare(OCusBusInfo.Gender,g, true) == 0)) { yield return new ValidationResult("性別只能是M/F之一", new string[] { "Gender" }); } }
5.讓資料型別實現IDataErrorInfo介面
public string this[string columnName] { get { switch (columnName) { case "Gender": { if (string.IsNullOrEmpty(this.Gender)) { return "'性別'是必需欄位"; } else if (!new string[] { "M", "F" }.Any(g => string.Compare(this.Gender, g, true) == { return "性別只能是M/F之一"; } return null; } default: return null; } } }