ValidateHelper.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using HaBookCms.ContextConfig.Exceptions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Text;
  7. namespace HaBookCms.Common.ValidateHelper
  8. {
  9. public static class ValidateHelper
  10. {
  11. public static string AllowCountry { get; set; }
  12. /// <summary>
  13. /// 验证对象是否有效
  14. /// </summary>
  15. /// <param name="obj">要验证的对象</param>
  16. /// <param name="validationResults"></param>
  17. /// <returns></returns>
  18. public static bool IsValid(this object obj, Collection<ValidationResult> validationResults)
  19. {
  20. return Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), validationResults, true);
  21. }
  22. /// <summary>
  23. /// 验证对象是否有效
  24. /// </summary>
  25. /// <param name="obj">要验证的对象</param>
  26. /// <returns></returns>
  27. public static bool IsValid(object value)
  28. {
  29. var results = new Collection<ValidationResult>();
  30. var validationContext = new ValidationContext(value, null, null);
  31. bool f= Validator.TryValidateObject(value, validationContext,results ,true);
  32. if (!f) {
  33. string s = "";
  34. foreach (ValidationResult result in results) {
  35. IEnumerator<string> enumerator= result.MemberNames.GetEnumerator();
  36. enumerator.MoveNext();
  37. s = s + enumerator.Current + ",";
  38. }
  39. throw new BizException(s+"字段不正确");
  40. }
  41. return f;
  42. }
  43. }
  44. }