|
1 | 1 | using System; |
2 | 2 | using System.Collections.Generic; |
3 | 3 | using System.ComponentModel.DataAnnotations; |
| 4 | +using System.Globalization; |
4 | 5 | using System.Linq; |
5 | 6 | using System.Text; |
6 | 7 |
|
7 | | -namespace IGLib |
| 8 | +namespace IGLib; |
| 9 | + |
| 10 | +public class ParsableStringValidator<TTarget> : IValidator<string> |
8 | 11 | { |
| 12 | + private readonly IStringParser<TTarget> _parser; |
9 | 13 |
|
10 | | - public class ParsableStringValidator<TTarget> : IValidator<string> |
| 14 | + public ParsableStringValidator( |
| 15 | + IFormatProvider formatProvider = null, |
| 16 | + string errorMessage = null) |
11 | 17 | { |
12 | | - private readonly IStringParser<TTarget> _parser; |
| 18 | + _parser = StringParserProvider.GetParser<TTarget>(formatProvider ?? CultureInfo.CurrentCulture); |
| 19 | + ErrorMessage = errorMessage ?? $"Value is not a valid {typeof(TTarget).Name}."; |
| 20 | + } |
13 | 21 |
|
14 | | - public ParsableStringValidator( |
15 | | - IFormatProvider? formatProvider = null, |
16 | | - string? errorMessage = null) |
17 | | - { |
18 | | - _parser = StringParserProvider.GetParser<TTarget>(formatProvider); |
19 | | - ErrorMessage = errorMessage ?? $"Value is not a valid {typeof(TTarget).Name}."; |
20 | | - } |
| 22 | + public string ErrorMessage { get; } |
21 | 23 |
|
22 | | - public string ErrorMessage { get; } |
| 24 | + public virtual void Validate(string value, ValidationResults results) |
| 25 | + { |
| 26 | + if (results == null) |
| 27 | + throw new ArgumentNullException(nameof(results)); |
23 | 28 |
|
24 | | - public virtual void Validate(string value, ValidationResults results) |
| 29 | + if (value == null) |
25 | 30 | { |
26 | | - // ToDo ArgumentNullException.ThrowIfNull(results); |
27 | | - |
28 | | - if (value == null) |
29 | | - { |
30 | | - results.AddError(ErrorMessage); |
31 | | - return; |
32 | | - } |
33 | | - |
34 | | - if (!_parser.TryParse(value, out _)) |
35 | | - results.AddError(ErrorMessage); |
| 31 | + results.AddError(ErrorMessage); |
| 32 | + return; |
36 | 33 | } |
| 34 | + |
| 35 | + if (!_parser.TryParse(value, out _)) |
| 36 | + results.AddError(ErrorMessage); |
37 | 37 | } |
38 | 38 | } |
0 commit comments