pub trait Validate {
const ERROR_BAG: Option<&'static str> = None;
// Required method
fn rules(&self, v: &mut Validator);
// Provided methods
fn prepare(&mut self) { ... }
fn authorize(
&self,
form: &FormContext<'_>,
) -> impl Future<Output = Result<bool>> + Send { ... }
fn after(
&self,
form: &FormContext<'_>,
errors: &mut Errors,
) -> impl Future<Output = Result> + Send { ... }
}Expand description
Declares the rules for a form. Used by the Valid<T> extractor, which
calls, in order: prepare,
authorize, rules and, when
they pass, after. Only rules is required.
use renox::validation::FormContext;
#[derive(serde::Deserialize)]
struct Invite { email: String, team_id: i64 }
impl Validate for Invite {
// Laravel's prepareForValidation: tidy the input first.
fn prepare(&mut self) {
self.email = self.email.trim().to_lowercase();
}
// Laravel's authorize: `false` answers 403 before any rule runs.
async fn authorize(&self, form: &FormContext<'_>) -> Result<bool> {
Ok(form.user.is_some_and(|user| user.has_role("owner")))
}
fn rules(&self, v: &mut Validator) {
v.field("email", &self.email).required().email();
}
// Laravel's `after`: checks that need the database or several fields,
// once the rules pass. Errors added here are shown like any other.
async fn after(&self, form: &FormContext<'_>, errors: &mut Errors) -> Result {
let members: i64 = renox::db::sql("SELECT COUNT(*) FROM team_user WHERE team_id = ?")
.bind(self.team_id)
.scalar(&form.state.db)
.await?;
if members >= 10 {
errors.add("email", "This team is full (10 members).");
}
Ok(())
}
}Provided Associated Constants§
Sourceconst ERROR_BAG: Option<&'static str> = None
const ERROR_BAG: Option<&'static str> = None
The named error bag this form’s errors are flashed in (Laravel’s
error bags), for a page with two forms that share field names, e.g.
Some("login") next to a sign-up form. Templates read them with
error('email', bag='login'). #[validate(bag = "login")] on a
derived struct sets it.
Required Methods§
Provided Methods§
Sourcefn prepare(&mut self)
fn prepare(&mut self)
Tidies the input before anything checks it (Laravel’s
prepareForValidation): trim, lowercase an email, fill a slug. The
form refilled after an error still shows what was typed.
Whether this request may send the form (Laravel’s authorize), e.g.
only the team’s owner invites. false answers 403 before the rules
run. It sees the input, so it runs once the input is read.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".