pub trait ValidatePattern {
    fn validate_pattern(&self, pattern: &Regex) -> Result<(), PatternError>;
}
Expand description

Pattern validation of the string.

See https://json-schema.org/understanding-json-schema/reference/string.html#regular-expressions

use serde_json::json;
use serde_valid::{Validate, ValidatePattern};

struct MyType(String);

impl ValidatePattern for MyType {
    fn validate_pattern(
        &self,
        pattern: &regex::Regex,
    ) -> Result<(), serde_valid::PatternError> {
        self.0.validate_pattern(pattern)
    }
}

#[derive(Validate)]
struct TestStruct {
    #[validate(pattern = r"^\d{4}-\d{2}-\d{2}$")]
    val: MyType,
}

let s = TestStruct {
    val: MyType(String::from("2020/09/10")),
};

assert_eq!(
    s.validate().unwrap_err().to_string(),
    json!({
        "errors": [],
        "properties": {
            "val": {
                "errors": [r#"The value must match the pattern of "^\d{4}-\d{2}-\d{2}$"."#]
            }
        }
    })
    .to_string()
);

Required Methods

Implementors