Trait semval::ValidatedFrom

source ·
pub trait ValidatedFrom<T>: Validate + Sized {
    fn validated_from(from: T) -> ValidatedResult<Self>;
}
Expand description

Value-to-value conversion with post-validation of the output value

On success the output value is returned. On validation errors the output value is returned together with all invalidities.

If validation of the output value has failed clients

  • may discard the output and abort,
  • are able to handle or fix the validation errors and continue, or
  • accept the output despite validation errors and continue.

The initial value-to-value conversion from input to output must always succeed.

The validation is performed on the output value after the input value has been consumed during the conversion. This post-validation approach should be applicable and sufficient for most use cases. It simplifies the validated result type by always returning the converted output independent of whether the validation succeeded or failed.

Example


struct Email(String);

#[derive(Debug)]
enum EmailInvalidity {
    MinLength,
    Format,
}

impl Validate for Email {
    type Invalidity = EmailInvalidity;
    fn validate(&self) -> ValidationResult<Self::Invalidity> {
        // ...custom implementation...
    }
}

let email = Email("test@example.com".to_string());
match Email::validated_from(email) {
    Ok(email) => println!("Valid e-mail address: {}", email.0),
    Err((email, context)) => println!("Invalid e-mail address: {} {:?}", email.0, context),
}

Required Methods

Convert input value into Self and validate self

Errors

Returns Err with the collected invalidities if one or more validations failed.

Implementors