Validating a form
A form's rules are written once in Rust. The browser checks them as the visitor types, and the handler checks the same rules before it trusts the values.
The Validate trait
The values T of a Form<T> implement Validate, which a Signals struct can implement:
pub trait Validate: Signals {
fn rules<S>(form: Sig<S, Self>, rules: &mut Rules<S, Self>) {}
}rules builds expressions from form, the values on whatever page S the form sits on, and adds them to rules. The default adds none, for a form that only needs its dirty state and reset: impl Validate for Note {}.
Rules
Rules::check adds one check: the field it belongs to, an expression that must be true, and the message shown while it is false.
pub fn check<U>(
&mut self,
field: Sig<T, U>,
ok: impl IntoExpr<S, bool>,
message: impl IntoExpr<S, String>,
) -> &mut SelfA field with several checks shows the message of the first one that fails, in the order they were added. A check may read every field of form, so one field can be compared with another. The message is an expression too, so it can hold a value the visitor typed.
use hypersig::{Form, Rules, Sig, Signals, Validate};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize, Clone, Default)]
struct Signup {
email: String,
password: String,
confirm: String,
}
impl Validate for Signup {
fn rules<S>(form: Sig<S, Self>, rules: &mut Rules<S, Self>) {
let email = form.at(Signup::email());
let password = form.at(Signup::password());
rules
// Two checks on one field: the first that fails gives the message.
.check(Signup::email(), !email.is_empty(), "Enter an email address.")
.check(Signup::email(), email.contains("@"), "That is not an email address.")
.check(Signup::password(), password.char_count().ge(8), "Use 8 or more characters.")
// A rule can read the other fields.
.check(
Signup::confirm(),
form.at(Signup::confirm()).equals(password),
"The passwords differ.",
);
}
}
// The server evaluates the same expressions.
let sent = Signup { email: "ada".into(), password: "short".into(), confirm: "other".into() };
let errors = Form::validate(&sent).unwrap_err();
assert_eq!(errors.message(Signup::email()), Some("That is not an email address."));
assert_eq!(errors.message(Signup::confirm()), Some("The passwords differ."));ok must be an expression of type bool on the same page, so a number where a condition belongs does not compile:
use hypersig::{Rules, Sig, Signals, Validate};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize, Clone)]
struct Signup {
password: String,
}
impl Validate for Signup {
fn rules<S>(form: Sig<S, Self>, rules: &mut Rules<S, Self>) {
let password = form.at(Signup::password());
// error[E0277]: `Expr<S, i32>` is not an expression of type `bool` on the page whose signals are `S`
rules.check(Signup::password(), password.char_count(), "Use 8 or more characters.");
}
}Checking on the server
rules is generic over the page S, so the same code builds the expressions twice. On the page, the browser evaluates them as the visitor types. In the handler, Form::validate evaluates them with the evaluator that writes the first HTML, so a value the browser accepted passes on the server too.
pub fn validate(value: &T) -> Result<(), FieldErrors<T>>It returns the message of the first failing rule of each field. Call it in the action handler: anyone can send the action's URL a request without loading the page, so the rules in the browser do not protect the handler.
// The handler checks the same rules, then what only the server knows.
async fn join((): (), value: Signup) -> Patches<Join> {
let signup = Join::signup();
if let Err(errors) = Form::validate(&value) {
return signup.reject(&errors).into();
}
if value.email == "taken@example.com" {
let taken = FieldErrors::new().add(Signup::email(), "That address is taken.");
return signup.reject(&taken).into();
}
// Saved: these values are the form's new starting values.
signup.patch(Form::new(value)).into()
}A patch of one field leaves the starting values alone, so a handler that has saved the values patches the whole form with Form::new(saved), as the last line does. The saved values become the new starting values, and the form forgets the fields the visitor has left, the submit, and the messages from the server.
Messages from the server
FieldErrors<T> holds a message per field of T. Form::validate returns one, and a handler builds one for what only the server can check, such as an address that is already taken.
| Item | What it does |
|---|---|
FieldErrors::new() | No messages |
add(field, message) | These messages, with message for field in place of any it had |
message(field) | The message for field, as Option<&str> |
is_empty() | Whether no field has a message |
Display | email: That address is taken., with ; between fields, for a log |
reject on the form's Sig turns them into a patch of the form's messages from the server, which a handler returns as signup.reject(&errors).into(). error(field) shows such a message where no rule of the field fails, and the next submit empties it.
is_valid() on the form's Sig is an Expr<S, bool> that is true while every rule passes, for a page that shows the state of the whole form, such as a hint beside the submit button.
What the compiler does not check
A rule that reads Expr::now or Expr::random_below compiles, but only the browser has those values, so Form::validate could not check it. check panics with a message that names the field and says the rule reads a value only the browser has. The rules are built while the page is, so the page panics before it is served.
Some values pass in the browser and fail on the server. A rule whose arithmetic leaves the finite range, such as a division by zero, or that reads a date outside the years 1000 to 9999, fails in Form::validate, with an empty message where the message cannot be evaluated either. A value that holds an infinite or NaN number, which an HTML form's inf or NaN parses to, fails every rule.
A handler that never calls Form::validate compiles, and then accepts whatever the request carries.
Next, Extractors and headers reads more of the request than the arguments, and Errors and logging covers a handler that fails.