Skip to main content
Version: 0.7.2

Virtual Fields

virtualinput only

A virtual field is an input-only field whose value may or may not be provided at creation, used to trigger a change in one or more dependent fields that depend on it -- it's validated/sanitized like a real field, but never stored on the output struct directly.

  • Declared with #[ivo_virtual], or #[ivo_virtual("alias")] to expose it under a different name on the generated input struct.
  • Must be referenced by at least one #[depends_on(...)] field -- either by its declared name, or by its alias if it has one.
  • Must have a validator via #[validate]; may also have a #[re_validate].
  • May have a #[sanitize(|value, ctx, opts| -> T)] mutator, run after validate/re-validate/post_validate succeed.
  • May leverage #[ignore], #[ignore_init] and #[ignore_update] provision rules.
  • May have on_failure and on_success event handlers.
  • Requires output(...) on the schema, since it never appears on the output struct.

Example: no alias​

A virtual sets its dependents but never appears in the output, and a provided virtual always triggers them, even when they end up unchanged:

main.rs
use ivo::ivo_schema;

#[ivo_schema(
input(UserInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(User, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod user_schema {
struct Fields {
#[ivo_virtual]
#[validate(|full_name: &String, _, _| {
if !full_name.contains(' ') {
return Err(("expected a first and a last name".into(), None));
}
Ok(None)
})]
pub full_name: String,

#[depends_on("full_name")]
#[default(String::new())]
#[resolve(|ctx, _| {
println!("(the first_name resolver ran)");
ctx.input().full_name.clone().unwrap().split(' ').next().unwrap().to_string()
})]
pub first_name: String,

#[depends_on("full_name")]
#[default(String::new())]
#[resolve(|ctx, _| {
ctx.input().full_name.clone().unwrap().split_once(' ').unwrap().1.to_string()
})]
pub last_name: String,
}
}

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

let full_name = || PartialUserInput { full_name: Some("Ada Lovelace".into()) };

// the virtual sets its dependents, but isn't part of the output
let (user, _) = UserModel.create(full_name(), ()).unwrap(); // (the first_name resolver ran)
println!("{:?}", user); // User { first_name: "Ada", last_name: "Lovelace" }

// a provided virtual always triggers its dependents, even when they end up unchanged
let (errors, _) = UserModel.update(user, full_name(), ()).unwrap_err(); // (the first_name resolver ran)
println!("{:?}", errors); // None
}

Example: aliased​

#[ivo_virtual("email_input")] exposes the field as email_input on the input struct, while the field itself is still named (and referenced by #[depends_on(...)]) as raw_email:

main.rs
use ivo::ivo_schema;

#[ivo_schema(
input(UserInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(User, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod user_schema {
struct Fields {
// `email_input` on the input struct
#[ivo_virtual("email_input")]
#[validate(|email: &String, _, _| {
if !email.contains('@') {
return Err(("invalid email".into(), None));
}
Ok(None)
})]
pub raw_email: String,

#[depends_on("raw_email")]
#[default(String::new())]
#[resolve(|ctx, _| ctx.input().email_input.clone().unwrap().to_lowercase())]
pub email: String,
}
}

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

let (user, _) = UserModel
.create(PartialUserInput { email_input: Some("Ada@Example.com".into()) }, ())
.unwrap();
println!("{:?}", user); // User { email: "ada@example.com" }
}

Note ctx.input().email_input above -- the input struct's field is named after the alias, not the virtual field's own declared name. #[depends_on("raw_email")] still uses the declared name (an alias may also depend on itself by its own name if it collides with an existing dependent field name -- see the alias-collision example below).

Conditional required​

main.rs
use ivo::ivo_schema;

#[ivo_schema(
input(AccountInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(Account, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod account_schema {
struct Fields {
#[lax("customer".to_string())]
pub role: String,

// required for affiliates
#[ivo_virtual]
#[validate(|code: &String, _, _| {
if !code.starts_with("SAVE") {
return Err(("invalid promo code".into(), None));
}
Ok(None)
})]
#[required(|ctx, _| {
(ctx.values().role.as_deref() == Some("affiliate") && ctx.input().promo_code.is_none())
.then(|| "Promo code is required for affiliates".into())
})]
pub promo_code: String,

#[depends_on("promo_code")]
#[default(0)]
#[resolve(|ctx, _| ctx.input().promo_code.clone().unwrap()[4..].parse().unwrap())]
pub discount: u32,
}
}

fn main() {
use account_schema::{AccountModel, PartialAccountInput};

let (errors, _) = AccountModel
.create(PartialAccountInput { role: Some("affiliate".into()), promo_code: None }, ())
.unwrap_err();
println!("{:?}", errors.get("promo_code").unwrap().reason); // "Promo code is required for affiliates"

let (account, _) = AccountModel
.create(
PartialAccountInput { role: Some("affiliate".into()), promo_code: Some("SAVE10".into()) },
(),
)
.unwrap();
println!("{:?}", account); // Account { role: "affiliate", discount: 10 }
}

Ignore rules​

A virtual takes the same ignore rules as a lax field (#[ignore(...)], #[ignore_init], #[ignore_update]). An ignored virtual doesn't trigger its dependents:

main.rs
use ivo::ivo_schema;

#[ivo_schema(
input(AccountInput, ivo_attrs(derive(Debug, Clone, PartialEq))),
output(Account, ivo_attrs(derive(Debug, Clone, PartialEq)))
)]
mod account_schema {
struct Fields {
#[lax(String::new())]
pub email: String,

// an invite code only counts at signup
#[ivo_virtual]
#[ignore_update]
#[validate(|code: &String, _, _| {
if code != "PRO" {
return Err(("invalid invite code".into(), None));
}
Ok(None)
})]
pub invite_code: String,

#[depends_on("invite_code")]
#[default("free".to_string())]
#[resolve(|_, _| "pro".to_string())]
pub plan: String,
}
}

fn main() {
use account_schema::{AccountModel, PartialAccountInput};

let (invited, _) = AccountModel
.create(
PartialAccountInput { email: Some("ada@example.com".into()), invite_code: Some("PRO".into()) },
(),
)
.unwrap();
println!("{:?}", invited); // Account { email: "ada@example.com", plan: "pro" }

let (account, _) = AccountModel
.create(PartialAccountInput { email: Some("grace@example.com".into()), invite_code: None }, ())
.unwrap();
let (errors, _) = AccountModel
.update(account, PartialAccountInput { email: None, invite_code: Some("PRO".into()) }, ())
.unwrap_err();
println!("{:?}", errors); // None
}

More examples​

Try it in the browser​

virtual_field is a virtual input field. The output dependent uses its value when provided, otherwise it falls back to a default. Leave virtual_field empty or remove it to see the default.

Loading playground…