[][src]Trait semval::ValidatedFrom

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

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 UnvalidatedEmail(String);

struct Email(String);

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

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

impl ValidatedFrom<UnvalidatedEmail> for Email {
    fn validated_from(from: UnvalidatedEmail) -> ValidatedResult<Self> {
        // 1st step: Convert value
        let from = Email(from.0);
        // 2nd step: Validate converted value
        if let Err(err) = from.validate() {
            Err((from, err))
        } else {
            Ok(from)
        }
    }
}

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

Required methods

pub fn validated_from(from: T) -> ValidatedResult<Self>[src]

Convert input value into Self and validate self

Loading content...

Implementors

impl<T> ValidatedFrom<T> for T where
    T: Validate
[src]

Loading content...