-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathJsonNumberValidator.cs
More file actions
67 lines (58 loc) · 2.38 KB
/
JsonNumberValidator.cs
File metadata and controls
67 lines (58 loc) · 2.38 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
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;
namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonNumberValidator : IJsonValidator
{
public bool CanValidate(OpenApiSchema schema) => schema.Type == "number";
public bool Validate(
OpenApiSchema schema,
OpenApiDocument openApiDocument,
JToken instance,
out IEnumerable<string> errorMessages)
{
if (instance.Type is not JTokenType.Float and not JTokenType.Integer)
{
errorMessages = [$"Path: {instance.Path}. Instance is not of type 'number'"];
return false;
}
var numberValue = instance.Value<decimal>();
var errorMessagesList = new List<string>();
// multipleOf
if (schema.MultipleOf.HasValue && ((numberValue % schema.MultipleOf.Value) != 0))
{
errorMessagesList.Add($"Path: {instance.Path}. Number is not evenly divisible by multipleOf");
}
// maximum & exclusiveMaximum
if (schema.Maximum.HasValue)
{
var exclusiveMaximum = schema.ExclusiveMaximum ?? false;
if (exclusiveMaximum && (numberValue >= schema.Maximum.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. Number is greater than, or equal to, maximum");
}
else if (numberValue > schema.Maximum.Value)
{
errorMessagesList.Add($"Path: {instance.Path}. Number is greater than maximum");
}
}
// minimum & exclusiveMinimum
if (schema.Minimum.HasValue)
{
var exclusiveMinimum = schema.ExclusiveMinimum ?? false;
if (exclusiveMinimum && (numberValue <= schema.Minimum.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. Number is less than, or equal to, minimum");
}
else if (numberValue < schema.Minimum.Value)
{
errorMessagesList.Add($"Path: {instance.Path}. Number is less than minimum");
}
}
errorMessages = errorMessagesList;
return !errorMessages.Any();
}
}
}