Read #[validate(...)] attributes

This commit is contained in:
Graham Esau 2021-03-29 16:38:55 +01:00
parent dada8582ee
commit 6ab567f3a5
13 changed files with 532 additions and 33 deletions

View file

@ -0,0 +1,81 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Struct",
"type": "object",
"required": [
"contains_str1",
"contains_str2",
"email_address",
"homepage",
"map_contains",
"min_max",
"non_empty_str",
"pair",
"regex_str1",
"regex_str2",
"required_option",
"tel"
],
"properties": {
"min_max": {
"type": "number",
"format": "float",
"maximum": 100.0,
"minimum": 0.01
},
"regex_str1": {
"type": "string",
"pattern": "^[Hh]ello\\b"
},
"regex_str2": {
"type": "string",
"pattern": "^[Hh]ello\\b"
},
"contains_str1": {
"type": "string",
"pattern": "substring\\.\\.\\."
},
"contains_str2": {
"type": "string",
"pattern": "substring\\.\\.\\."
},
"email_address": {
"type": "string",
"format": "email"
},
"tel": {
"type": "string",
"format": "phone"
},
"homepage": {
"type": "string",
"format": "uri"
},
"non_empty_str": {
"type": "string",
"maxLength": 100,
"minLength": 1
},
"pair": {
"type": "array",
"items": {
"type": "integer",
"format": "int32"
},
"maxItems": 2,
"minItems": 2
},
"map_contains": {
"type": "object",
"required": [
"map_key"
],
"additionalProperties": {
"type": "null"
}
},
"required_option": {
"type": "boolean"
}
}
}

View file

@ -0,0 +1,40 @@
mod util;
use schemars::JsonSchema;
use std::collections::HashMap;
use util::*;
// In real code, this would typically be a Regex, potentially created in a `lazy_static!`.
static STARTS_WITH_HELLO: &'static str = r"^[Hh]ello\b";
#[derive(Debug, JsonSchema)]
pub struct Struct {
#[validate(range(min = 0.01, max = 100))]
min_max: f32,
#[validate(regex = "STARTS_WITH_HELLO")]
regex_str1: String,
#[validate(regex(path = "STARTS_WITH_HELLO", code = "foo"))]
regex_str2: String,
#[validate(contains = "substring...")]
contains_str1: String,
#[validate(contains(pattern = "substring...", message = "bar"))]
contains_str2: String,
#[validate(email)]
email_address: String,
#[validate(phone)]
tel: String,
#[validate(url)]
homepage: String,
#[validate(length(min = 1, max = 100))]
non_empty_str: String,
#[validate(length(equal = 2))]
pair: Vec<i32>,
#[validate(contains = "map_key")]
map_contains: HashMap<String, ()>,
#[validate(required)]
required_option: Option<bool>,
}
#[test]
fn validate() -> TestResult {
test_default_generated_schema::<Struct>("validate")
}