|
| 1 | +using System.ComponentModel.DataAnnotations; |
| 2 | + |
| 3 | +namespace StructTest; |
| 4 | + |
| 5 | +public static class ValidationTest |
| 6 | +{ |
| 7 | + |
| 8 | + #region Constants & Statics |
| 9 | + |
| 10 | + public static void ValidationAllow() |
| 11 | + { |
| 12 | + var product = new Product |
| 13 | + { |
| 14 | + Price = 100_000.00m, |
| 15 | + Price2 = 0.01m, |
| 16 | + Price3 = 1000000000000000, // no error, is wrong! |
| 17 | + Price4 = 999_999_999_999_999.99981m // no error |
| 18 | + }; |
| 19 | + var context = new ValidationContext(product); |
| 20 | + var results = new List<ValidationResult>(); |
| 21 | + |
| 22 | + var isValid = Validator.TryValidateObject(product, context, results, true); |
| 23 | + |
| 24 | + if (!isValid) |
| 25 | + { |
| 26 | + foreach (var error in results) |
| 27 | + { |
| 28 | + Console.WriteLine($"{string.Join(',', error.MemberNames)} : {error.ErrorMessage}"); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public static void ValidationError() |
| 34 | + { |
| 35 | + var product = new Product |
| 36 | + { |
| 37 | + Price = -1.00m, |
| 38 | + Price2 = 0.001m, |
| 39 | + Price3 = 999_999_999_999_999.99991m, // no error, is wrong! |
| 40 | + Price4 = 999_999_999_999_999.99991m // error |
| 41 | + }; |
| 42 | + var context = new ValidationContext(product); |
| 43 | + var results = new List<ValidationResult>(); |
| 44 | + |
| 45 | + var isValid = Validator.TryValidateObject(product, context, results, true); |
| 46 | + |
| 47 | + if (!isValid) |
| 48 | + { |
| 49 | + foreach (var error in results) |
| 50 | + { |
| 51 | + Console.WriteLine($"{string.Join(',', error.MemberNames)} : {error.ErrorMessage}"); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + #endregion |
| 57 | + |
| 58 | + public class Product |
| 59 | + { |
| 60 | + |
| 61 | + #region Properties |
| 62 | + |
| 63 | + [Range(0.01, 100_000.00, ErrorMessage = "价格必须在0.01到100,000.00之间")] |
| 64 | + public decimal Price { get; set; } |
| 65 | + |
| 66 | + [Range(typeof(decimal), "0.01", "100000.00")] |
| 67 | + [DataType(DataType.Currency)] |
| 68 | + [DisplayFormat(DataFormatString = "{0:C2}")] |
| 69 | + public decimal Price2 { get; set; } |
| 70 | + |
| 71 | + [Range(0.0001, 999_999_999_999_999.9999)] // 超过 double 有效位数,between 0.0001 and 1000000000000000 |
| 72 | + public decimal Price3 { get; set; } |
| 73 | + |
| 74 | + [Range(typeof(decimal), "0.0001", "999999999999999.9999")] |
| 75 | + public decimal Price4 { get; set; } |
| 76 | + |
| 77 | + #endregion |
| 78 | + } |
| 79 | +} |
0 commit comments