macro_rules! fast_rule { ($name:ident, msg = $msg:expr, $func:expr) => { ... }; ($name:ty, err = $err:tt, msg = $msg:expr, $func:expr) => { ... }; }
Expand description
Define a rule using a predicate with ad-hoc errors.
This is done by implementing ValidateString
for your
rule using the closure. Since ValidateString
expects
your closure to return Result<(), Error>
(where Error
refers
to some choice of an error type), fast_rule
converts your closure’s return type to Result<(), Error>
so that true
is mapped to Ok(())
and false
is mapped
to your error type or error message.
The error type is:
&'static str
with themsg
value if you don’t specify theerr
parameter.- Your error type
err
if you do specify theerr
parameter.
See also
easy_rule
is more flexible in that it allows you to construct your own error instance so you can throw errors that are neither ZSTs nor implementingDebug + Display + Error
.ValidateString
Example
use validus::prelude::*;
use validus::fast_rule;
// 1. String errors.
// The error type is &'static str.
// 1a. Define your rule. I called it Email.
struct Email;
// 1b. Implement ValidateString for your rule
// using fast_rule!.
fast_rule!(Email, msg = "invalid email", |s: &str| {
s.contains('@')
});
// 1c. Try it out.
let vv: &vstr<Email> = "hello@world".validate::<Email>().unwrap();
// 2. Your error type.
// fast_rule! implements Debug + Display + Error.
// Both the Debug and Display errors are made to display the string
// "invalid phone number".
// 2a. Define your error type. Make it a ZST.
// fast_rule! will implement Debug, Display, and Error for you.
struct BadPhoneError;
// 2b. Define your rule.
struct Phone;
// 2c. Implement ValidateString for your rule.
fast_rule!(Phone,
err = BadPhoneError,
msg = "invalid phone number",
|s: &str| {
s.len() == 11 && s.starts_with("07")
}
);
// 2d. Try it out:
let vv: &vstr<Phone> = "07123456789".validate::<Phone>().unwrap();
assert_eq!(vv, "07123456789");
let vv: BadPhoneError = "123".validate::<Phone>().unwrap_err();
assert_eq!(vv.to_string(), "invalid phone number");