ValidateHelper.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.ComponentModel.DataAnnotations;
  5. namespace TEAMModelOS.SDK.Helper.Common.ValidateHelper
  6. {
  7. public static class ValidateHelper
  8. {
  9. public static string AllowCountry { get; set; }
  10. /// <summary>
  11. /// 验证对象是否有效
  12. /// </summary>
  13. /// <param name="obj">要验证的对象</param>
  14. /// <param name="validationResults"></param>
  15. /// <returns></returns>
  16. public static bool IsValid(this object obj, Collection<ValidationResult> validationResults)
  17. {
  18. return Validator.TryValidateObject(obj, new ValidationContext(obj, null, null), validationResults, true);
  19. }
  20. /// <summary>
  21. /// 验证对象是否有效
  22. /// </summary>
  23. /// <param name="obj">要验证的对象</param>
  24. /// <returns></returns>
  25. public static T ValidObj<T>(T value)
  26. {
  27. var results = new Collection<ValidationResult>();
  28. var validationContext = new ValidationContext(value, null, null);
  29. bool f = Validator.TryValidateObject(value, validationContext, results, true);
  30. if (f)
  31. {
  32. return value;
  33. }
  34. else
  35. {
  36. return default;
  37. }
  38. }
  39. /// <summary>
  40. /// 验证对象是否有效
  41. /// </summary>
  42. /// <param name="obj">要验证的对象</param>
  43. /// <returns></returns>
  44. public static bool IsValid(object value)
  45. {
  46. var results = new Collection<ValidationResult>();
  47. var validationContext = new ValidationContext(value, null, null);
  48. bool f = Validator.TryValidateObject(value, validationContext, results, true);
  49. if (!f)
  50. {
  51. string s = "";
  52. foreach (ValidationResult result in results)
  53. {
  54. IEnumerator<string> enumerator = result.MemberNames.GetEnumerator();
  55. enumerator.MoveNext();
  56. s = s + enumerator.Current + ",";
  57. }
  58. throw new Exception(s + "字段不正确");
  59. }
  60. return f;
  61. }
  62. }
  63. }