diff options
| author | Vincent Prouillet | 2017-01-18 01:26:44 +0900 |
|---|---|---|
| committer | Vincent Prouillet | 2017-01-18 01:26:44 +0900 |
| commit | 3de07e80ed2d961bc0b07d7971a04c590f0a8290 (patch) | |
| tree | 2f7c51f7bb88191078bde2cce0a0e772f6370452 /validator_derive | |
| parent | 32ada012eb1de7da60d979b65844d008fc75b458 (diff) | |
| download | validator-3de07e80ed2d961bc0b07d7971a04c590f0a8290.tar.bz2 | |
Add regex validator
Diffstat (limited to 'validator_derive')
| -rw-r--r-- | validator_derive/Cargo.toml | 2 | ||||
| -rw-r--r-- | validator_derive/src/lib.rs | 14 | ||||
| -rw-r--r-- | validator_derive/tests/test_derive.rs | 20 |
3 files changed, 36 insertions, 0 deletions
diff --git a/validator_derive/Cargo.toml b/validator_derive/Cargo.toml index e5234f9..0738262 100644 --- a/validator_derive/Cargo.toml +++ b/validator_derive/Cargo.toml @@ -20,6 +20,8 @@ serde = "0.8" serde_derive = "0.8" serde_json = "0.8" compiletest_rs = "0.2" +regex = "0.2" +lazy_static = "0.2" [dependencies.validator] path = "../validator" diff --git a/validator_derive/src/lib.rs b/validator_derive/src/lib.rs index 7a21ac8..68a4b2e 100644 --- a/validator_derive/src/lib.rs +++ b/validator_derive/src/lib.rs @@ -129,6 +129,14 @@ fn expand_validation(ast: &syn::MacroInput) -> quote::Tokens { } ) }, + &Validator::Regex(ref re) => { + let re_ident = syn::Ident::new(re.clone()); + quote!( + if !#re_ident.is_match(&self.#field_ident) { + errors.add(#name, "regex"); + } + ) + }, }); } } @@ -437,6 +445,12 @@ fn find_validators_for_field(field: &syn::Field, field_types: &HashMap<String, S None => error("invalid argument for `contains` validator: only strings are allowed"), }; }, + "regex" => { + match lit_to_string(val) { + Some(s) => validators.push(Validator::Regex(s)), + None => error("invalid argument for `regex` validator: only strings are allowed"), + }; + } "must_match" => { match lit_to_string(val) { Some(s) => { diff --git a/validator_derive/tests/test_derive.rs b/validator_derive/tests/test_derive.rs index c7e78cc..4e6c088 100644 --- a/validator_derive/tests/test_derive.rs +++ b/validator_derive/tests/test_derive.rs @@ -2,8 +2,11 @@ extern crate validator; #[macro_use] extern crate serde_derive; extern crate serde_json; +extern crate regex; +#[macro_use] extern crate lazy_static; use validator::Validate; +use regex::Regex; #[derive(Debug, Validate, Deserialize)] @@ -251,3 +254,20 @@ fn test_can_fail_contains_validation() { assert!(errs.contains_key("mail")); assert_eq!(errs["mail"], vec!["contains".to_string()]); } + +#[test] +fn test_can_check_regex_validator() { + lazy_static! { + static ref RE: Regex = Regex::new(r"[a-z]{2}").unwrap(); + } + + #[derive(Debug, Validate)] + struct RegexStruct { + #[validate(regex = "RE")] + name: String, + } + let s = RegexStruct {name: "al".to_string()}; + assert!(s.validate().is_ok()); + let s2 = RegexStruct {name: "AL".to_string()}; + assert!(s2.validate().is_err()); +} |
