Skip to main content

CustomValidate

Trait CustomValidate 

Source
pub trait CustomValidate<P>: Sized {
    // Required method
    fn custom_validate(&mut self) -> Option<P>;
}
Expand description

Custom whole-form validation, opted into with #[validatable(custom_validate)].

When a type derives Validatable with the custom_validate attribute, calling validate() dispatches to this trait (implemented by you for T<Form>) instead of the derived per-field validation. Implementations typically call Validatable::validate_by, which first runs the derived validation and then lets you add cross-field rules:

A cross-field rule enforced here only holds for T<Plain> values that were actually produced by validate() — it is not tracked by the type system. T<Plain> is a struct, and a struct literal is a constructor like any other: if its fields are pub, calling code can assemble independently valid field values into a combination this trait never checked, with or without custom_validate being called. Keep the fields private (exposing read accessors instead) whenever the invariant must hold unconditionally.

use validatable::*;

#[derive(Validatable, PartialEq, Clone, Debug)]
#[validatable(custom_validate)]
struct Range<F: FieldFamily> {
    low: Field<F, i32>,
    high: Field<F, i32>,
}

impl CustomValidate<Range<Plain>> for Range<Form> {
    fn custom_validate(&mut self) -> Option<Range<Plain>> {
        Range::<Plain>::validate_by(self, |form, value, c| {
            if let Some(v) = value {
                if v.low > v.high {
                    form.low.fail(c, Message::Text("must be <= high".into()));
                }
            }
        })
    }
}

let mut form = Range::<Form>::default();
form.low.input("5".to_string());
form.high.input("1".to_string());
assert_eq!(form.validate(), None);
assert_eq!(form.low.message, Some(Message::Text("must be <= high".into())));

form.high.input("9".to_string());
assert_eq!(form.validate(), Some(Range { low: 5, high: 9 }));

Required Methods§

Source

fn custom_validate(&mut self) -> Option<P>

Validates the form and returns the plain value when it is valid.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§