-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathJsonStringValidator.cs
More file actions
50 lines (43 loc) · 1.73 KB
/
JsonStringValidator.cs
File metadata and controls
50 lines (43 loc) · 1.73 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
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;
namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonStringValidator : IJsonValidator
{
public bool CanValidate(OpenApiSchema schema) => schema.Type == JsonSchemaTypes.String;
public bool Validate(
OpenApiSchema schema,
OpenApiDocument openApiDocument,
JToken instance,
out IEnumerable<string> errorMessages)
{
if (instance.Type is not JTokenType.Date and not JTokenType.Guid and not JTokenType.String)
{
errorMessages = [$"Path: {instance.Path}. Instance is not of type 'string'"];
return false;
}
var stringValue = instance.Value<string>();
var errorMessagesList = new List<string>();
// maxLength
if (schema.MaxLength.HasValue && (stringValue.Length > schema.MaxLength.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. String length is greater than maxLength");
}
// minLength
if (schema.MinLength.HasValue && (stringValue.Length < schema.MinLength.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. String length is less than minLength");
}
// pattern
if ((schema.Pattern != null) && !Regex.IsMatch(stringValue, schema.Pattern))
{
errorMessagesList.Add($"Path: {instance.Path}. String does not match pattern");
}
errorMessages = errorMessagesList;
return !errorMessages.Any();
}
}
}