When a form is wrong, the server has to say which field and why, and the page has to show it beside that field. In this chapter we'll validate one input with the validator crate, send its errors back across a redirect, and look at what the page receives.
This chapter assumes Chapter 3, since errors travel the same way flash data does. It covers the validator feature. The crate has a garde feature too, which this chapter does not exercise.
Sending errors back
The validator found two things wrong with the name field and said so, in order. The page was given the first. The second stayed in the session, correct and unread.
Sometimes validation fails and the right response is the form the user was on, with the messages attached. Thankfully, that is one call. Take a look at Example 4-1.
Example 4-1. Validate, then go back with errors
#[derive(Deserialize, Validate)]
pub struct Remind {
#[validate(email(message = "Enter an email address."))]
pub to: String,
}
pub async fn remind(inertia: Inertia, Form(input): Form<Remind>) -> Response {
if let Err(errors) = input.validate() {
return inertia.back_with_errors(errors).into_response();
}
inertia.flash("notice", Flash { level: FlashLevel::Success, body: "Reminder sent".into() });
inertia::redirect("/invoices/7").into_response()
}
There are two new pieces here. input.validate() comes from the validator crate and returns its own error type. back_with_errors accepts anything that converts into this crate's ValidationErrors, and with the validator feature on, that error type does. It shares the errors with the next page and redirects to the Referer, or to / when there isn't one.
The next page receives them in a prop named errors, keyed by field (see Example 4-2).
Example 4-2. The errors prop
{"errors":{"to":"Enter an email address."}}
By default each field carries its first message as a string. You can also send every message per field, as an array, with Config::all_errors(true).
If a rule has no message of its own, the conversion writes one from the field's name, in the form "The to field is invalid." If you're unsure whether to rely on that, I'd give every rule a message; the fallback knows the field and nothing about the rule.
You can also build errors by hand, without either validation crate: ValidationErrors::new().with("to", "Enter an email address.").
What this chapter leaves open
So a bad address comes back as one message beside one field. Now put two forms on the page, each with a field called to. The crate has error bags for this: with_errors_in files errors under a bag's name, and the client asks for a bag with a request header. Which of your pages already has two forms? Did anyone decide what the second one's errors are called?
Testing
Example 4-3 fails if the error is lost across the redirect, and it fails if the success notice is flashed anyway.
Example 4-3. A bad address
let request = visit("POST", "/invoices/7/remind")
.header("referer", "/invoices/7")
.header("content-type", "application/x-www-form-urlencoded")
.body(Body::from("to=nobody"))
.unwrap();
let reply = send(&app, request).await;
let cookie = reply.cookie.expect("a session cookie");
let reply = send(&app, visit("GET", "/invoices/7").header(header::COOKIE, &cookie).body(Body::empty()).unwrap()).await;
AssertablePage::from_body(&reply.body)
.equals("errors.to", "Enter an email address.")
.missing_flash("notice");
TL;DR
back_with_errors shares validation errors with the next page and redirects back. The page receives an errors prop keyed by field, holding the first message per field unless all_errors is set. The validator and garde features convert those crates' errors; ValidationErrors can also be built by hand. Error bags separate the errors of two forms on one page.