Skip to main content
Version: 0.8.0

Validators

A validator assesses (and may transform) a field's value. Lax, required and virtual fields can each have up to two: a primary #[validate] and a secondary #[re_validate], which only runs once the primary validator has already succeeded.

Both share the same signature: |value: &T, ctx, opts| -> Result<Option<T>, (IvoErrorReason, Option<Metadata>)>. The value is borrowed, so accepting it as-is never copies it.

  • Ok(None) accepts the value as-is.
  • Ok(Some(new_value)) replaces it.
  • Err((reason, metadata)) rejects it -- metadata is None unless you're using a custom IvoErrorSanitizer. reason is an IvoErrorReason: a literal ("too short".into()) is used as-is, without allocating, and a message built at runtime works too (format!("...").into()).
main.rs
use ivo::ivo_schema;

#[ivo_schema(input(User, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod user_schema {
struct Fields {
#[required]
// the format
#[validate(|username: &String, _, _| {
if username.len() < 3 {
return Err(("username too short".into(), None));
}
Ok(None)
})]
// only for well-formed usernames, on create and on update
#[re_validate(|username: &String, ctx, _| {
println!("(checking {:?} on {})", username, if ctx.is_update() { "update" } else { "create" });
if username == "grace" {
return Err(("username taken".into(), None));
}
Ok(None)
})]
pub username: String,
}
}

fn main() {
use user_schema::{PartialUser, UserModel};

let username = |name: &str| PartialUser { username: Some(name.into()) };

// the validator fails: the re-validator doesn't run
let errors = UserModel.create(username("ab")).unwrap_err();
println!("{:?}", errors.get("username").unwrap().reason); // "username too short"

let user = UserModel.create(username("ada")).unwrap(); // (checking "ada" on create)
println!("{:?}", user); // User { username: "ada" }

let errors = UserModel.update(user, username("grace")).unwrap_err(); // (checking "grace" on update)
println!("{:?}", errors.unwrap().get("username").unwrap().reason); // "username taken"
}

since v0.6.1 A field can have #[re_validate] without #[validate]. See it used for real (checking a username isn't already taken, via ctx_options) in examples/main_demo.

Built-in validation helpers​

Enable the optional validators feature (ivo = { version = "*", features = ["validators"] }, crate ivo-validators) for a small set of built-in validators:

  • validate_email(value: &str) -> Result<String, String>
  • validate_credit_card(value: &str) -> Result<String, String>
#[lax(None)]
#[validate(|v: &Option, _, _| {
let Some(email) = v else { return Ok(None) };
match validate_email(&email) {
Ok(validated) => Ok(Some(Some(validated))),
Err(e) => Err((e.into(), None)),
}
})]
pub email: Option<String>,

See the crate source for implementation details, and main_demo for a schema that uses them.