-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckAttribute.cs
More file actions
107 lines (92 loc) · 2.82 KB
/
CheckAttribute.cs
File metadata and controls
107 lines (92 loc) · 2.82 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public enum CheckType
{
NotEmpty,
ParsesTo,
OneOf,
OneOfSupportedTypes
}
public class CheckAttribute : Attribute
{
private Dictionary<CheckType, Action<List<string>, string, string>> checkers;
public CheckAttribute(CheckType checkType)
{
CheckType = checkType;
InitializeCheckers();
}
public CheckAttribute(CheckType checkType, Type enumType)
{
CheckType = checkType;
EnumType = enumType;
InitializeCheckers();
}
public CheckAttribute(CheckType checkType, params string[] options)
{
CheckType = checkType;
Options = options;
InitializeCheckers();
}
public CheckType CheckType { get; }
public string[] Options { get; }
public Type EnumType { get; }
public void Validate(List<string> errors, string name, object value)
{
var s = value as string;
checkers[CheckType](errors, name, s);
}
private void InitializeCheckers()
{
checkers = new Dictionary<CheckType, Action<List<string>, string, string>>
{
{ CheckType.NotEmpty, NotEmpty },
{ CheckType.ParsesTo, ParsesTo },
{ CheckType.OneOf, OneOf },
{ CheckType.OneOfSupportedTypes , OneOfSupportedTypes },
};
}
private void NotEmpty(List<string> errors, string name, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
errors.Add(GetPrefix(name, value) + "Field cannot be empty.");
}
}
private void ParsesTo(List<string> errors, string name, string value)
{
if (!Enum.TryParse(EnumType, value, out var result))
{
errors.Add(GetPrefix(name, value) + "Invalid. Options are: " + GetEnumOptions());
}
}
private void OneOf(List<string> errors, string name, string value)
{
if (!Options.Contains(value))
{
errors.Add(GetPrefix(name, value) + "Invalid. Options are: " + string.Join(", ", Options.Select(Surround)));
}
}
private void OneOfSupportedTypes(List<string> errors, string name, string value)
{
var types = TypeUtils.GetSupportedTypes();
if (!types.Contains(value))
{
errors.Add(GetPrefix(name, value) + "Invalid. Options are: " + string.Join(", ", types.Select(Surround)));
}
}
private string GetPrefix(string name, string value)
{
return "[" + name + " = '" + value + "'] ";
}
private string GetEnumOptions()
{
var members = EnumType.GetMembers(BindingFlags.Public | BindingFlags.Static);
return string.Join(", ", members.Select(m => Surround(m.Name)));
}
private string Surround(string s)
{
return "'" + s + "'";
}
}