forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFluentValidationModelValidator.cs
More file actions
60 lines (50 loc) · 2.25 KB
/
FluentValidationModelValidator.cs
File metadata and controls
60 lines (50 loc) · 2.25 KB
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
using ServiceStack.FluentValidation;
using ServiceStack.FluentValidation.Internal;
using ServiceStack.FluentValidation.Results;
namespace FluentValidation.Mvc {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
/// <summary>
/// ModelValidator implementation that uses FluentValidation.
/// </summary>
internal class FluentValidationModelValidator : ModelValidator {
readonly IValidator validator;
readonly CustomizeValidatorAttribute customizations;
public FluentValidationModelValidator(ModelMetadata metadata, ControllerContext controllerContext, IValidator validator)
: base(metadata, controllerContext) {
this.validator = validator;
this.customizations = CustomizeValidatorAttribute.GetFromControllerContext(controllerContext)
?? new CustomizeValidatorAttribute();
}
public override IEnumerable<ModelValidationResult> Validate(object container) {
if (Metadata.Model != null) {
var selector = customizations.ToValidatorSelector();
var interceptor = customizations.GetInterceptor() ?? (validator as IValidatorInterceptor);
var context = new ValidationContext(Metadata.Model, new PropertyChain(), selector);
if(interceptor != null) {
// Allow the user to provide a customized context
// However, if they return null then just use the original context.
context = interceptor.BeforeMvcValidation(ControllerContext, context) ?? context;
}
var result = validator.Validate(context);
if(interceptor != null) {
// allow the user to provice a custom collection of failures, which could be empty.
// However, if they return null then use the original collection of failures.
result = interceptor.AfterMvcValidation(ControllerContext, context, result) ?? result;
}
if (!result.IsValid) {
return ConvertValidationResultToModelValidationResults(result);
}
}
return Enumerable.Empty<ModelValidationResult>();
}
protected virtual IEnumerable<ModelValidationResult> ConvertValidationResultToModelValidationResults(ValidationResult result) {
return result.Errors.Select(x => new ModelValidationResult {
MemberName = x.PropertyName,
Message = x.ErrorMessage
});
}
}
}