Trait validus::vstr::ValidateString
source · pub trait ValidateString: Send + Sync + Unpin {
type Error;
// Required method
fn validate_str(s: &str) -> Result<(), Self::Error>;
}
Expand description
Validate a string slice.
A type (preferably a ZST) that implements this trait
has a function validate_str
that can be called on
any str
-slice to validate it, according to the rules
that the type claims to enforce.
There’s also the special implementations:
ValidateAll
: that validates everything, and()
: that validates nothing.
Example
In this example, the use of a regular expression to validate a simple email address is shown.
Here, I will use a simplified email scheme that just checks
whether there are characters before and after an at-sign (@
)
all throughout the string slice.
use std::sync::OnceLock;
use regex::Regex;
use validus::prelude::ValidateString;
const REGEX: &str = r"^.+@.+$";
static RE_EMAIL: OnceLock<Regex> = OnceLock::new();
// This is my rule.
struct Email;
// And, this is how I implement it.
impl ValidateString for Email {
type Error = ();
fn validate_str(s: &str) -> Result<(), Self::Error> {
// I use a `OnceLock` to lazily compile the regex.
let re = RE_EMAIL.get_or_init(|| Regex::new(REGEX).unwrap());
// ... then, `is_match` to check whether the string slice
// matches the regex.
re.is_match(s).then(|| ()).ok_or(())
}
}
// Now, I can call `validate_str` on a string slice.
assert!(Email::validate_str("hello@world").is_ok());
// Very well. Now, a counter-example.
assert!(Email::validate_str("hello world").is_err());
// Note that, however, each implementation of `ValidateString`
// is meant to be used by `VStr`.
About Into
Using Into
, you can express: “If RuleA
validates a string slice,
then RuleB
also validates the same string slice.”
Specifically, if RuleA: Into<RuleB>
, then VStr<RuleA>
can be
converted to VStr<RuleB>
without the possibility of error
using the VStr::change_rules
method.
See VStr::change_rules
and VStr::erase_rules
for more information.
(There’s also VStr::try_change_rules
, which
is a fallible version of VStr::change_rules
that works for any pair of rules.)
Into
is incomplete
Idetally, all ValidateString
implementations should
implement Into<ValidateAll>
.
However, this is not possible because of the orphan rule, so here’s a workaround:
- To convert a
vstr<_>
tovstr<ValidateAll>
, useVStr::erase_rules
. - Also, to convert a
vstr<()>
tovstr<_>
, useVStr::try_change_rules
.
See also
Required Associated Types§
Required Methods§
Implementations on Foreign Types§
source§impl ValidateString for ()
impl ValidateString for ()
A special implementation that validates nothing.
Implementors§
source§impl ValidateString for StringAsciiRule
impl ValidateString for StringAsciiRule
type Error = StringHadNonAsciiError
source§impl ValidateString for ValidateAll
impl ValidateString for ValidateAll
A special implementation that validates everything.