-
Notifications
You must be signed in to change notification settings - Fork 124
/
ExpressiveAnnotationsModelValidatorProvider.cs
60 lines (55 loc) · 2.81 KB
/
ExpressiveAnnotationsModelValidatorProvider.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
/* https://github.com/JaroslawWaliszko/ExpressiveAnnotations
* Copyright (c) 2014 Jaroslaw Waliszko
* Licensed MIT: http://opensource.org/licenses/MIT */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ExpressiveAnnotations.Attributes;
using ExpressiveAnnotations.MvcUnobtrusive.Validators;
namespace ExpressiveAnnotations.MvcUnobtrusive.Providers
{
/// <summary>
/// Data annotations validator provider which automatically registers adapters for expressive validation attributes, i.e. <see cref="ExpressiveAttribute" />,
/// and additionally respects their processing priorities (if <see cref="ExpressiveAttribute.Priority" /> is specified) when validation is executed.
/// </summary>
/// <remarks>
/// Attributes with highest priority (lowest value) will be processed in first place. Attributes without explicitly proivided priorities will be processed later,
/// without any specific order.
/// </remarks>
public class ExpressiveAnnotationsModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
/// <summary>
/// Initializes a new instance of the <see cref="ExpressiveAnnotationsModelValidatorProvider"/> class.
/// </summary>
public ExpressiveAnnotationsModelValidatorProvider()
{
RegisterAdapter(typeof(RequiredIfAttribute), typeof(RequiredIfValidator));
RegisterAdapter(typeof(AssertThatAttribute), typeof(AssertThatValidator));
}
/// <summary>
/// Gets a list of validators.
/// </summary>
/// <param name="metadata">The metadata.</param>
/// <param name="context">The context.</param>
/// <param name="attributes">The list of validation attributes.</param>
/// <returns>
/// A list of validators.
/// </returns>
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
{
var allAttribs = attributes.ToList();
var orderedAttribs = allAttribs
.Where(x => x is ExpressiveAttribute)
.Cast<ExpressiveAttribute>()
.Where(x => x.GetPriority().HasValue)
.OrderBy(x => x.Priority)
.Cast<Attribute>()
.ToList();
var setToRemove = new HashSet<Attribute>(orderedAttribs);
allAttribs.RemoveAll(setToRemove.Contains); // allAttribs variable contains only chaotic attribs now
orderedAttribs.AddRange(allAttribs); // chaotic attribs are added after ordered ones
return base.GetValidators(metadata, context, orderedAttribs);
}
}
}