Required Fields
requiredinput and output
A required field is both an input and output field whose value must be provided at creation (e.g.
username). It's optional (and immutable unless explicitly allowed) on update.
- Declared with the bare
#[required]field-type attribute. - Must have a validator via
#[validate]; may also have a#[re_validate]. - May customize the missing-field error via
#[required_error(...)]-- a static string or a|raw_input, opts| -> Stringclosure. - May leverage
#[ignore_update](resolver form only) and#[readonly]to prevent further updates. - May have
on_deleteandon_successevent handlers, andon_failure.
Example
main.rs
use ivo::ivo_schema;
#[ivo_schema(input(User, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod user_schema {
struct Fields {
#[required]
#[validate(|username: &String, _, _| {
if username.len() < 3 {
return Err(("username too short".into(), None));
}
Ok(None)
})]
pub username: String,
#[lax(String::new())]
pub bio: String,
}
}
fn main() {
use user_schema::{PartialUser, UserModel};
// missing on create: an error
let errors = UserModel
.create(PartialUser { username: None, bio: Some("Hi!".into()) })
.unwrap_err();
println!("{:?}", errors.get("username").unwrap().reason); // "field is required"
let user = UserModel
.create(PartialUser { username: Some("ada".into()), bio: None })
.unwrap();
println!("{:?}", user); // User { username: "ada", bio: "" }
// an update doesn't have to provide it
let updated = UserModel
.update(user, PartialUser { username: None, bio: Some("Hi!".into()) })
.unwrap();
println!("{:?}", updated); // PartialUser { username: None, bio: Some("Hi!") }
}
Custom required error
#[required_error(...)] takes a static message, or a |raw_input, opts| closure computing one:
main.rs
use ivo::ivo_schema;
#[derive(Debug, Clone)]
pub struct Locale(pub &'static str);
#[ivo_schema(input(User, ivo_attrs(derive(Debug, Clone, PartialEq))), ctx_options(super::Locale))]
mod user_schema {
struct Fields {
// a static message
#[required]
#[required_error("Email is required")]
#[validate(|_: &String, _, _| Ok(None))]
pub email: String,
// or one computed from the input and the ctx options
#[required]
#[required_error(|_raw_input, opts| {
if opts.read_sync().0 == "fr" {
"Le nom d'utilisateur est requis"
} else {
"Username is required"
}
})]
#[validate(|_: &String, _, _| Ok(None))]
pub username: String,
}
}
fn main() {
use user_schema::{PartialUser, UserModel};
let (errors, _ctx_options) = UserModel
.create(PartialUser { email: None, username: None }, Locale("fr"))
.unwrap_err();
println!("{:?}", errors.get("email").unwrap().reason); // "Email is required"
println!("{:?}", errors.get("username").unwrap().reason); // "Le nom d'utilisateur est requis"
}
Readonly
#[readonly] ignores every update of the field: it keeps the value it was created with.
main.rs
use ivo::ivo_schema;
#[ivo_schema(input(Account, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod account_schema {
struct Fields {
#[required]
#[validate(|number: &String, _, _| {
if number.len() != 8 {
return Err(("expected 8 digits".into(), None));
}
Ok(None)
})]
#[readonly]
pub account_number: String,
#[lax(String::new())]
pub label: String,
}
}
fn main() {
use account_schema::{AccountModel, PartialAccount};
let account = AccountModel
.create(PartialAccount { account_number: Some("12345678".into()), label: None })
.unwrap();
println!("{:?}", account); // Account { account_number: "12345678", label: "" }
// a readonly field never changes once created
let updated = AccountModel
.update(
account,
PartialAccount {
account_number: Some("87654321".into()),
label: Some("Savings".into()),
},
)
.unwrap();
println!("{:?}", updated); // PartialAccount { account_number: None, label: Some("Savings") }
}
Ignore update
#[ignore_update(|ctx, opts| ...)] ignores the field's updates while the handler returns true:
main.rs
use ivo::ivo_schema;
#[ivo_schema(input(User, ivo_attrs(derive(Debug, Clone, PartialEq))))]
mod user_schema {
struct Fields {
// a verified user's username can't change anymore
#[required]
#[validate(|_: &String, _, _| Ok(None))]
#[ignore_update(|ctx, _| ctx.values().verified == Some(true))]
pub username: String,
#[lax(false)]
pub verified: bool,
}
}
fn main() {
use user_schema::{PartialUser, User, UserModel};
let rename = || PartialUser { username: Some("new_name".into()), verified: None };
let unverified = User { username: "ada".into(), verified: false };
let updated = UserModel.update(unverified, rename()).unwrap();
println!("{:?}", updated); // PartialUser { username: Some("new_name"), verified: None }
let verified = User { username: "grace".into(), verified: true };
let errors = UserModel.update(verified, rename()).unwrap_err();
println!("{:?}", errors); // None
}
More examples
Try it in the browser
username is required with no other constraints - leave the input empty to see the required
error, or provide a value to see it accepted.
Loading playground…