valid8/
lib.rs

1#![warn(
2    missing_docs,
3    rust_2018_idioms,
4    clippy::pedantic,
5    missing_debug_implementations
6)]
7#![cfg_attr(docsrs, feature(doc_cfg))]
8
9//! # Valid8
10//! A simple validation library.
11//!
12//! # Example
13//!
14//! Use the validators to validate values.
15//! ```rust
16//! use valid8::Validator;
17//! use valid8::validator::Min;
18//!
19//! let validator = Min::<u32>::new(5);
20//! let invalid = "1234";
21//! assert!(validator.validate(&invalid).is_err());
22//!
23//! let valid = "12345";
24//! assert!(validator.validate(&valid).is_ok());
25//! ```
26//!
27//! Use the `derive(Validate)` macro to generate validation code for structs.
28
29#![cfg_attr(
30    feature = "derive",
31    doc = r#"
32```rust
33use valid8::Validate;
34
35#[derive(Validate)]
36struct User {
37    #[validate(required)]
38    username: String,
39    #[validate(required, email)]
40    email: String,
41    #[validate(required, min(8))]
42    password: String,
43}
44
45let valid = User {
46    username: String::from("Joe"),
47    email: String::from("joe@example.com"),
48    password: String::from("12345678"),
49};
50
51assert!(valid.validate().is_ok());
52
53let invalid = User {
54    username: String::from(""),
55    email: String::from("joe@example"),
56    password: String::from("1234567"),
57};
58
59assert!(invalid.validate().is_err());
60```
61"#
62)]
63
64/// Validators for different types.
65pub mod validator;
66
67pub use regex;
68pub use validator::Validator;
69
70#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
71#[cfg(feature = "derive")]
72pub use valid8_derive::Validate;
73
74#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
75#[cfg(feature = "derive")]
76/// The error returned by the validate method generated by the `derive(Validate)` macro.
77#[derive(Debug)]
78pub enum ValidationError {
79    /// The field specified by `0` failed [`validator::Required`] validation.
80    Missing(String),
81    /// Some field failed [`validator::Email`] validation.
82    Email,
83    /// The field specified by `0` failed [`validator::Min`] validation.
84    Min(String),
85}
86
87#[cfg(feature = "derive")]
88impl std::fmt::Display for ValidationError {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        match self {
91            ValidationError::Email => f.write_str("Invalid email."),
92            ValidationError::Missing(field) => {
93                f.write_fmt(format_args!("Missing required field `{field}`."))
94            }
95            ValidationError::Min(field) => f.write_fmt(format_args!(
96                "Field `{field}` failed minimum size validation."
97            )),
98        }
99    }
100}