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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
#[macro_use]
extern crate validator_derive;
extern crate validator;
use validator::{Validate, ValidationError};
fn valid_custom_fn(_: &str) -> Result<(), ValidationError> {
Ok(())
}
fn invalid_custom_fn(_: &str) -> Result<(), ValidationError> {
Err(ValidationError::new("meh"))
}
#[test]
fn can_validate_custom_fn_ok() {
#[derive(Debug, Validate)]
struct TestStruct {
#[validate(custom = "valid_custom_fn")]
val: String,
}
let s = TestStruct {
val: "hello".to_string(),
};
assert!(s.validate().is_ok());
}
#[test]
fn can_fail_custom_fn_validation() {
#[derive(Debug, Validate)]
struct TestStruct {
#[validate(custom = "invalid_custom_fn")]
val: String,
}
let s = TestStruct {
val: String::new(),
};
let res = s.validate();
assert!(res.is_err());
let errs = res.unwrap_err().inner();
assert!(errs.contains_key("val"));
assert_eq!(errs["val"].len(), 1);
assert_eq!(errs["val"][0].code, "meh");
assert_eq!(errs["val"][0].params["value"], "");
}
#[test]
fn can_specify_message_for_custom_fn() {
#[derive(Debug, Validate)]
struct TestStruct {
#[validate(custom(function = "invalid_custom_fn", message = "oops"))]
val: String,
}
let s = TestStruct {
val: String::new(),
};
let res = s.validate();
assert!(res.is_err());
let errs = res.unwrap_err().inner();
assert!(errs.contains_key("val"));
assert_eq!(errs["val"].len(), 1);
assert_eq!(errs["val"][0].clone().message.unwrap(), "oops");
}
|