Skip to content

Commit 9f49389

Browse files
committed
add data-annotations docs
1 parent 10d388a commit 9f49389

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

.jekyll-metadata

3.37 KB
Binary file not shown.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
layout: page
3+
title: JSON Schema Generation with System.ComponentModel.DataAnnotations
4+
bookmark: Data Annotations
5+
permalink: /schema/schemagen/:title/
6+
icon: fas fa-tag
7+
order: "01.5.3"
8+
---
9+
The _System.ComponentModel.DataAnnotations_ namespace defines numerous attributes that are commonly used within ASP.Net and other areas to validate data models.
10+
11+
The primary downside to using this approach is that the JSON has to be deserialized into the model before validation can occur.
12+
13+
An alternative is to generate a JSON Schema from the model. The _JsonSchema.Net.Generation.DataAnnotations_ library is an extension on _JsonSchema.Net.Generation_ to support the _System.ComponentModel.DataAnnotations_ attributes.
14+
15+
> It's important to understand that the DataAnnotations attributes are not as flexible as the attributes defined in the main library. For advanced schema features, using the main library attributes is imperative.
16+
{: .prompt-warning}
17+
18+
## Usage
19+
20+
In order to generate constraints from the DataAnnotations attributes, you'll need to first register the handlers.
21+
22+
```c#
23+
DataAnnotationsSupport.AddDataAnnotations();
24+
```
25+
26+
## Supported attributes
27+
28+
The following attributes are supported:
29+
30+
|Attribute|Description of support|
31+
|:-|:-|
32+
|`[AllowedValues()]`|Produces an `enum` keyword with the indicated values. (.Net 8 only)|
33+
|`[DeniedValues()]`|Produces a `not: { enum: []}` keyword construct with the indicated values. (.Net 8 only)|
34+
|`[Base64String]`|Produces a `format: base64` keyword. Note that this format is defined by OpenAPI but not JSON Schema.|
35+
|`[EmailAddress]`|Produces a `format: email` keyword.|
36+
|`[EnumDataType()]`|Produces an `enum` keyword with the values of the C# enum type supplied in the attribute.|
37+
|`[Length()]`|Produces `minLength` and/or `maxLength` keywords.|
38+
|`[MaxLength()]`|Produces a `maxLength` keyword.|
39+
|`[MinLength()]`|Produces a `minLength` keyword.|
40+
|`[Range()]`|Produces `minimum` and/or `maximum` keywords.|
41+
|`[RegularExpression()]`|Produces a `pattern` keyword.|
42+
|`[StringLength()]`|Produces `minLength` and/or `maxLength` keywords.|
43+
|`[UrlAttribute]`|Produces a `format: uri` keyword.|

0 commit comments

Comments
 (0)