-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
RuleComponent.cs
267 lines (220 loc) · 9.48 KB
/
RuleComponent.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#region License
// Copyright (c) .NET Foundation and contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at https://github.com/FluentValidation/FluentValidation
#endregion
namespace FluentValidation.Internal {
using System;
using System.Threading;
using System.Threading.Tasks;
using Validators;
public interface IRuleComponent<T, out TProperty> : IRuleComponent {
/// <summary>
/// The error code associated with this rule component.
/// </summary>
new string ErrorCode { get; set; }
/// <summary>
/// Function used to retrieve custom state for the validator
/// </summary>
Func<ValidationContext<T>, TProperty, object> CustomStateProvider { set; }
/// <summary>
/// Function used to retrieve the severity for the validator
/// </summary>
Func<ValidationContext<T>, TProperty, Severity> SeverityProvider { set; }
/// <summary>
/// Adds a condition for this validator. If there's already a condition, they're combined together with an AND.
/// </summary>
/// <param name="condition"></param>
void ApplyCondition(Func<ValidationContext<T>, bool> condition);
/// <summary>
/// Adds a condition for this validator. If there's already a condition, they're combined together with an AND.
/// </summary>
/// <param name="condition"></param>
void ApplyAsyncCondition(Func<ValidationContext<T>, CancellationToken, Task<bool>> condition);
/// <summary>
/// Sets the overridden error message template for this validator.
/// </summary>
/// <param name="errorFactory">A function for retrieving the error message template.</param>
void SetErrorMessage(Func<ValidationContext<T>, TProperty, string> errorFactory);
/// <summary>
/// Sets the overridden error message template for this validator.
/// </summary>
/// <param name="errorMessage">The error message to set</param>
void SetErrorMessage(string errorMessage);
/// <summary>
/// Sets the on failure callback.
/// </summary>
Action<T, ValidationContext<T>, TProperty, string> OnFailure { set; }
}
/// <summary>
/// An individual component within a rule.
/// In a rule definition such as RuleFor(x => x.Name).NotNull().NotEqual("Foo")
/// the NotNull and the NotEqual are both rule components.
/// </summary>
public class RuleComponent<T,TProperty> : IRuleComponent<T, TProperty> {
private string _errorMessage;
private Func<ValidationContext<T>, TProperty, string> _errorMessageFactory;
private Func<ValidationContext<T>, bool> _condition;
private Func<ValidationContext<T>, CancellationToken, Task<bool>> _asyncCondition;
private readonly IPropertyValidator<T, TProperty> _propertyValidator;
private readonly IAsyncPropertyValidator<T, TProperty> _asyncPropertyValidator;
internal RuleComponent(IPropertyValidator<T, TProperty> propertyValidator) {
_propertyValidator = propertyValidator;
}
internal RuleComponent(IAsyncPropertyValidator<T, TProperty> asyncPropertyValidator, IPropertyValidator<T, TProperty> propertyValidator) {
_asyncPropertyValidator = asyncPropertyValidator;
_propertyValidator = propertyValidator;
}
[Obsolete("The Options property will be removed in FluentValidation 11. All properties from Options should be accessed directly on this component instead.")]
public RuleComponent<T, TProperty> Options => this;
/// <inheritdoc />
public bool HasCondition => _condition != null;
/// <inheritdoc />
public bool HasAsyncCondition => _asyncCondition != null;
/// <inheritdoc />
public virtual IPropertyValidator Validator {
get {
if (_propertyValidator is ILegacyValidatorAdaptor l) {
return l.UnderlyingValidator;
}
return (IPropertyValidator) _propertyValidator ?? _asyncPropertyValidator;
}
}
private protected virtual bool SupportsAsynchronousValidation
=> _asyncPropertyValidator != null;
private protected virtual bool SupportsSynchronousValidation
=> _propertyValidator != null;
internal bool ShouldValidateAsynchronously(IValidationContext context) {
// If ValidateAsync has been invoked on the root validator, then always prefer
// the asynchronous property validator (if available).
if (context.IsAsync) {
if (SupportsAsynchronousValidation) {
return true;
}
// Fallback to sync if no async validator available.
return false;
}
// If Validate has been invoked on the root validator, then always prefer
// the synchronous validator.
if (SupportsSynchronousValidation) {
return false;
}
// Fall back to sync-over-async if only an async validator is available.
return true;
}
internal virtual bool Validate(ValidationContext<T> context, TProperty value)
=> _propertyValidator.IsValid(context, value);
internal virtual Task<bool> ValidateAsync(ValidationContext<T> context, TProperty value, CancellationToken cancellation)
=> _asyncPropertyValidator.IsValidAsync(context, value, cancellation);
/// <summary>
/// Adds a condition for this validator. If there's already a condition, they're combined together with an AND.
/// </summary>
/// <param name="condition"></param>
public void ApplyCondition(Func<ValidationContext<T>, bool> condition) {
if (_condition == null) {
_condition = condition;
}
else {
var original = _condition;
_condition = ctx => condition(ctx) && original(ctx);
}
}
/// <summary>
/// Adds a condition for this validator. If there's already a condition, they're combined together with an AND.
/// </summary>
/// <param name="condition"></param>
public void ApplyAsyncCondition(Func<ValidationContext<T>, CancellationToken, Task<bool>> condition) {
if (_asyncCondition == null) {
_asyncCondition = condition;
}
else {
var original = _asyncCondition;
_asyncCondition = async (ctx, ct) => await condition(ctx, ct) && await original(ctx, ct);
}
}
internal bool InvokeCondition(ValidationContext<T> context) {
if (_condition != null) {
return _condition(context);
}
return true;
}
internal async Task<bool> InvokeAsyncCondition(ValidationContext<T> context, CancellationToken token) {
if (_asyncCondition != null) {
return await _asyncCondition(context, token);
}
return true;
}
/// <summary>
/// Function used to retrieve custom state for the validator
/// </summary>
public Func<ValidationContext<T>, TProperty, object> CustomStateProvider { get; set; }
/// <summary>
/// Function used to retrieve the severity for the validator
/// </summary>
public Func<ValidationContext<T>, TProperty, Severity> SeverityProvider { get; set; }
/// <summary>
/// Retrieves the error code.
/// </summary>
public string ErrorCode { get; set; }
/// <summary>
/// Gets the error message. If a context is supplied, it will be used to format the message if it has placeholders.
/// If no context is supplied, the raw unformatted message will be returned, containing placeholders.
/// </summary>
/// <param name="context">The validation context.</param>
/// <param name="value">The current property value.</param>
/// <returns>Either the formatted or unformatted error message.</returns>
public string GetErrorMessage(ValidationContext<T> context, TProperty value) {
// Use a custom message if one has been specified.
string rawTemplate = _errorMessageFactory?.Invoke(context, value) ?? _errorMessage;
// If no custom message has been supplied, use the default.
if (rawTemplate == null) {
rawTemplate = Validator.GetDefaultMessageTemplate(ErrorCode);
}
if (context == null) {
return rawTemplate;
}
return context.MessageFormatter.BuildMessage(rawTemplate);
}
/// <summary>
/// Gets the raw unformatted error message. Placeholders will not have been rewritten.
/// </summary>
/// <returns></returns>
public string GetUnformattedErrorMessage() {
string message = _errorMessageFactory?.Invoke(null, default) ?? _errorMessage;
// If no custom message has been supplied, use the default.
if (message == null) {
message = Validator.GetDefaultMessageTemplate(ErrorCode);
}
return message;
}
/// <summary>
/// Sets the overridden error message template for this validator.
/// </summary>
/// <param name="errorFactory">A function for retrieving the error message template.</param>
public void SetErrorMessage(Func<ValidationContext<T>, TProperty, string> errorFactory) {
_errorMessageFactory = errorFactory;
_errorMessage = null;
}
/// <summary>
/// Sets the overridden error message template for this validator.
/// </summary>
/// <param name="errorMessage">The error message to set</param>
public void SetErrorMessage(string errorMessage) {
_errorMessage = errorMessage;
_errorMessageFactory = null;
}
public Action<T, ValidationContext<T>, TProperty, string> OnFailure { get; set; }
}
}