-
Notifications
You must be signed in to change notification settings - Fork 0
/
IValidatable.cs
91 lines (79 loc) · 2.53 KB
/
IValidatable.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
using System;
using System.Collections.Generic;
namespace CloudWorker.Client.SDK;
[AttributeUsage(AttributeTargets.Property)]
public class RequiredAttribute : Attribute
{
public RequiredAttribute() { }
}
[AttributeUsage(AttributeTargets.Property)]
public class ValidateCollectionAttribute : Attribute
{
public ValidateCollectionAttribute() { }
}
[AttributeUsage(AttributeTargets.Property)]
public class ValidateObjectAttribute : Attribute
{
public ValidateObjectAttribute() { }
}
public class ValidationError : ApplicationException
{
public string Error { get; }
public ValidationError(string error)
{
Error = error;
}
public override string ToString()
{
return $"ValidationError: {Error}";
}
}
public interface IValidatable
{
void Validate();
//TODO: Unit test
static void Validate(object obj)
{
var type = obj.GetType();
var properties = type.GetProperties();
foreach (var property in properties)
{
var attr = property.GetCustomAttributes(typeof(RequiredAttribute), true);
if (attr.Length > 0)
{
var value = property.GetValue(obj);
if (value == null)
{
throw new ValidationError($"The property {property.Name} cannot be null.");
}
if (value is string str && string.IsNullOrEmpty(str))
{
throw new ValidationError($"The property {property.Name} cannot be empty.");
}
}
//TODO: Validate properties of type IEnumerable<IValidatable> or IValidatable by default
//and remove ValidateCollectionAttribute and ValidateObjectAttribute?
attr = property.GetCustomAttributes(typeof(ValidateCollectionAttribute), true);
if (attr.Length > 0)
{
var collection = (IEnumerable<IValidatable>?)property.GetValue(obj);
if (collection != null)
{
foreach (var value in collection)
{
value.Validate();
}
}
}
attr = property.GetCustomAttributes(typeof(ValidateObjectAttribute), true);
if (attr.Length > 0)
{
var validatable = (IValidatable?)property.GetValue(obj);
if (validatable != null)
{
validatable.Validate();
}
}
}
}
}