Rule

Trait Rule 

Source
pub trait Rule<T: ?Sized>: Send + Sync {
    // Required methods
    fn validate(
        &self,
        value: &T,
        ctx: &ValidationContext,
    ) -> ValidationResult<()>;
    fn name(&self) -> &'static str;
    fn default_message(&self) -> String;

    // Provided methods
    fn validate_at(
        &self,
        value: &T,
        path: &FieldPath,
        ctx: &ValidationContext,
    ) -> ValidationResult<()> { ... }
    fn error_code(&self) -> String { ... }
    fn is_transform(&self) -> bool { ... }
}
Expand description

Trait for individual validation rules.

Each validation rule (email, length, range, etc.) implements this trait. Rules are generic over the value type they validate.

§Example

use skp_validator_core::{Rule, ValidationContext, ValidationResult};

struct MinLengthRule {
    min: usize,
}

impl Rule<str> for MinLengthRule {
    fn validate(&self, value: &str, _ctx: &ValidationContext) -> ValidationResult<()> {
        if value.len() >= self.min {
            Ok(())
        } else {
            Err(ValidationErrors::from_error(
                ValidationError::new("", "length.min", "Too short")
            ))
        }
    }

    fn name(&self) -> &'static str { "min_length" }
    fn default_message(&self) -> String { format!("Must be at least {} characters", self.min) }
}

Required Methods§

Source

fn validate(&self, value: &T, ctx: &ValidationContext) -> ValidationResult<()>

Validate the value.

Source

fn name(&self) -> &'static str

Get the rule name for error reporting.

Source

fn default_message(&self) -> String

Get the default error message.

Provided Methods§

Source

fn validate_at( &self, value: &T, path: &FieldPath, ctx: &ValidationContext, ) -> ValidationResult<()>

Validate the value with a field path for error reporting.

Source

fn error_code(&self) -> String

Get the error code.

Source

fn is_transform(&self) -> bool

Check if this rule is a transformation (not validation).

Implementors§

Source§

impl<T: ?Sized + Sync> Rule<T> for AnyRule<T>

Source§

impl<T: ?Sized + Sync> Rule<T> for CompositeRule<T>