Skip to main content

Form

Struct Form 

Source
pub struct Form<T> { /* private fields */ }
Expand description

The values of a form, the values it started from, and what the visitor has done to it.

Put one in the page’s signal struct as a field of type Form<T>, where T is a Signals struct of the form’s values that implements Validate. The methods on Sig<S, Form<T>> then read and change it: field binds a control, error gives the message to show under it, form checks the rules before calling an action, and reset puts the starting values back.

A form is dirty while its values differ from the values it started from. A Sig::patch of one field from the server changes the value and leaves the starting values alone, so the form stays dirty. A handler that has saved the values patches the whole form with Form::new(saved), which makes the saved values the new starting values and clears what the visitor has done.

use hypersig::html::{button, input};
use hypersig::{Action, Form, Page, Rules, Sig, Signals, Validate};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize, Clone)]
struct Signup {
    email: String,
}

impl Validate for Signup {
    fn rules<S>(form: Sig<S, Self>, rules: &mut Rules<S, Self>) {
        let email = form.at(Signup::email());
        rules.check(Signup::email(), email.contains("@"), "Enter an email address.");
    }
}

#[derive(Signals, Serialize, Deserialize)]
struct Join {
    signup: Form<Signup>,
}

const JOIN: Action<Join, Signup> = Action::post("/join");

let signup = Join::signup();
let email = Signup::email();
let page = Page::new("Join", Join { signup: Form::new(Signup { email: String::new() }) })
    .child(
        signup
            .form(JOIN.call_with(signup.value()))
            .child(input().bind(signup.field(email)).on_blur(signup.touch(email)))
            .child(button().attr("type", "submit").text("Join")),
    );
assert!(page.render().contains("signup.touched.email"));

Implementations§

Source§

impl<T: Clone> Form<T>

Source

pub fn new(value: T) -> Self

A form that starts from value, untouched and not yet submitted.

Source§

impl<T: Validate> Form<T>

Source

pub fn validate(value: &T) -> Result<(), FieldErrors<T>>

Checks value against the rules of T on the server.

The rules are the ones the browser checks, evaluated by the same evaluator that writes the first HTML, so a value the browser accepted passes here too. Call it in the action handler, because a request can come from something other than the page.

The exception is a rule the server cannot evaluate for the value it received: arithmetic whose result is not finite, such as a division by zero, or a date outside the years 1000 to 9999. That rule fails here, with an empty message where its message cannot be evaluated either, though the browser may have accepted the value. A value holding an infinite or NaN number, which an HTML form’s inf or NaN parses to, fails every rule.

§Errors

Returns the message of the first failing rule of each field.

§Panics

Panics if a rule reads Expr::now or Expr::random_below, which only the browser can evaluate, or if value fails to serialize.

use hypersig::{Form, Rules, Sig, Signals, Validate};
use serde::{Deserialize, Serialize};

#[derive(Signals, Serialize, Deserialize)]
struct Signup {
    email: String,
}

impl Validate for Signup {
    fn rules<S>(form: Sig<S, Self>, rules: &mut Rules<S, Self>) {
        let email = form.at(Signup::email());
        rules.check(Signup::email(), email.contains("@"), "Enter an email address.");
    }
}

let errors = Form::validate(&Signup { email: "ada".to_owned() }).unwrap_err();
assert_eq!(errors.message(Signup::email()), Some("Enter an email address."));
assert!(Form::validate(&Signup { email: "ada@example.com".to_owned() }).is_ok());

Trait Implementations§

Source§

impl<T: Clone> Clone for Form<T>

Source§

fn clone(&self) -> Form<T>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for Form<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, T> Deserialize<'de> for Form<T>
where T: Deserialize<'de>,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T> Serialize for Form<T>
where T: Serialize,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Form<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Form<T>
where T: RefUnwindSafe,

§

impl<T> Send for Form<T>
where T: Send,

§

impl<T> Sync for Form<T>
where T: Sync,

§

impl<T> Unpin for Form<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for Form<T>
where T: UnsafeUnpin,

§

impl<T> UnwindSafe for Form<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FromRef<T> for T
where T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.