diff --git a/schemars/tests/expected/validate.json b/schemars/tests/expected/validate.json index f5a6fc2..0878e84 100644 --- a/schemars/tests/expected/validate.json +++ b/schemars/tests/expected/validate.json @@ -13,6 +13,7 @@ "pair", "regex_str1", "regex_str2", + "regex_str3", "required_option", "tel", "x" @@ -32,6 +33,10 @@ "type": "string", "pattern": "^[Hh]ello\\b" }, + "regex_str3": { + "type": "string", + "pattern": "^\\d+$" + }, "contains_str1": { "type": "string", "pattern": "substring\\.\\.\\." diff --git a/schemars/tests/validate.rs b/schemars/tests/validate.rs index 00d1b57..ca704a7 100644 --- a/schemars/tests/validate.rs +++ b/schemars/tests/validate.rs @@ -14,6 +14,8 @@ pub struct Struct { regex_str1: String, #[validate(regex(path = "STARTS_WITH_HELLO", code = "foo"))] regex_str2: String, + #[validate(regex(pattern = r"^\d+$"))] + regex_str3: String, #[validate(contains = "substring...")] contains_str1: String, #[validate(contains(pattern = "substring...", message = "bar"))] diff --git a/schemars_derive/src/attr/validation.rs b/schemars_derive/src/attr/validation.rs index db72f31..8594db1 100644 --- a/schemars_derive/src/attr/validation.rs +++ b/schemars_derive/src/attr/validation.rs @@ -2,7 +2,7 @@ use super::parse_lit_str; use proc_macro2::TokenStream; use syn::ExprLit; use syn::NestedMeta; -use syn::{Expr, Lit, Meta, MetaNameValue, Path}; +use syn::{Expr, Lit, Meta, MetaNameValue}; #[derive(Debug, Default)] pub struct ValidationAttrs { @@ -11,7 +11,7 @@ pub struct ValidationAttrs { pub length_equal: Option, pub range_min: Option, pub range_max: Option, - pub regex: Option, + pub regex: Option, pub contains: Option, pub required: bool, pub format: Option<&'static str>, @@ -84,7 +84,9 @@ impl ValidationAttrs { path, lit: Lit::Str(regex), .. - })) if path.is_ident("regex") => self.regex = parse_lit_str(regex).ok(), + })) if path.is_ident("regex") => { + self.regex = parse_lit_str::(regex).ok().map(Expr::Path) + } NestedMeta::Meta(Meta::List(meta_list)) if meta_list.path.is_ident("regex") => { self.regex = meta_list.nested.iter().find_map(|x| match x { @@ -92,7 +94,17 @@ impl ValidationAttrs { path, lit: Lit::Str(regex), .. - })) if path.is_ident("path") => parse_lit_str(regex).ok(), + })) if path.is_ident("path") => { + parse_lit_str::(regex).ok().map(Expr::Path) + } + NestedMeta::Meta(Meta::NameValue(MetaNameValue { + path, + lit: Lit::Str(regex), + .. + })) if path.is_ident("pattern") => Some(Expr::Lit(syn::ExprLit { + attrs: Vec::new(), + lit: Lit::Str(regex.clone()), + })), _ => None, }); }