Struct HtmlForm

Source
pub struct HtmlForm<'a> {
    pub action: &'a str,
    pub method: Method,
    pub errors: HashMap<String, String>,
    pub fields: Vec<Field<'a>>,
}
Expand description

HtmlForm represents an HTML form. It is used to validate data (both on the server and the client side) and to serialize forms in a consistent manner (either as JSON or using a template language of choice). The builder-style API makes it relatively easy to define forms:

use es_htmlform::HtmlForm;
use es_htmlform::value::ValueMap;
use es_htmlform::types::{Method, InputType, Constraint, Attr};

fn main() {
    // user input
    let values = ValueMap::from_urlencoded(b"foo=bar").unwrap();
    let mut form = HtmlForm::new(".", Method::Post)
        .input(
            InputType::Text, "foo", "Foo", true,
            vec![], vec![]).unwrap()
        .submit(None, "Submit", vec![]).unwrap();
    form.update(&values, true);
    assert_eq!(form.errors.len(), 0);
    assert_eq!(form.get_string("foo").unwrap(), "bar");
}

Fields§

§action: &'a str§method: Method§errors: HashMap<String, String>§fields: Vec<Field<'a>>

Implementations§

Source§

impl<'a> HtmlForm<'a>

Source

pub fn new(action: &'a str, method: Method) -> HtmlForm<'a>

Instantiate an HtmlForm.

Source

pub fn update(&mut self, values: &ValueMap, check_required: bool)

Validate the values in a ValueMap and save them on the form

This populates self.errors and the values in self.fields, the latter regardless of whether the values are valid (this to allow presenting a form with errors with the old values pre-filled - note that password fields are emptied on serialization).

Example:

use es_htmlform::HtmlForm;
use es_htmlform::value::ValueMap;
use es_htmlform::types::{Method, InputType, Constraint};

fn main() {
    let mut form = HtmlForm::new(".", Method::Post)
        .input(
            InputType::Text, "foo", "Foo", true,
            vec![Constraint::MinLength(5)], vec![]).unwrap();
    form.update(
        &ValueMap::from_urlencoded(b"foo=bar").unwrap(), true);
    assert_eq!(
        form.errors.get("foo").unwrap(),
        "Must be at least 5 characters long.");
    assert_eq!(form.get::<String>("foo").unwrap(), vec!["bar"]);
}
Source

pub fn field(self, name: &str) -> Result<Field<'a>, FormError>

Return a Field by name, or an error if there is not field by that name.

Source

pub fn get<T>(&self, name: &str) -> Result<Vec<T>, FormError>
where T: FromStr,

Return a list of values of a field, parsed to T. Returns an error when the field is not found, when the values can not be converted (parsed) or when the field has no value.

Source

pub fn getone<T>(&self, name: &str) -> Result<T, FormError>
where T: FromStr,

Return a single value for a field, parsed to T. Returns an error when the field is not found, when more than one value is found, when the value can not be converted (parsed) or when the field has no value.

Source

pub fn get_strings(&self, name: &str) -> Result<Vec<String>, FormError>

Return a list of values of a field, as Strings. Returns an error when the field is not found or when the field has no value.

Source

pub fn get_string(&self, name: &str) -> Result<String, FormError>

Return a single value for a field as String. Returns an error when the field is not found, when more than one value is found, or when the field has no value.

Source

pub fn input( self, input_type: InputType, name: &'a str, label: &'a str, required: bool, constraints: Vec<Constraint<'a>>, attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create an input element, use this for non-collection fields (so not for InputType::Radio or InputType::Checkbox, for those see choice_input()). Returns self, so calls can be chained.

Source

pub fn checkbox( self, name: &'a str, label: &'a str, required: bool, choices: &'a [(&'a str, &'a str)], attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a set of checkboxes. Returns self, so calls can be chained.

Source

pub fn radio( self, name: &'a str, label: &'a str, required: bool, choices: &'a [(&'a str, &'a str)], attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a set of radio buttons. Returns self, so calls can be chained.

Source

pub fn datalist_input( self, input_type: InputType, name: &'a str, label: &'a str, required: bool, datalist: &'a [(&'a str, &'a str)], attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a text(-style) input with datalist for auto-fill suggestions. Returns self, so calls can be chained.

Source

pub fn hidden( self, name: &'a str, value: Option<&str>, required: bool, constraints: Vec<Constraint<'a>>, attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Source

pub fn textarea( self, name: &'a str, label: &'a str, required: bool, constraints: Vec<Constraint<'a>>, attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a textarea without validation. Returns self, so calls can be chained.

Source

pub fn select( self, name: &'a str, label: &'a str, multi: bool, required: bool, choices: &'a [(&'a str, &'a str)], attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a select dropdown. Returns self, so calls can be chained.

Source

pub fn submit( self, name: Option<&'a str>, label: &'a str, attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a submit button. Returns self, so calls can be chained.

Source

pub fn reset( self, label: &'a str, attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a reset button. Returns self, so calls can be chained.

Source

pub fn button( self, button_type: ButtonType, name: &'a str, label: &'a str, attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Shortcut to create a button element. Returns self, so calls can be chained.

Source

pub fn element( self, element: Element, name: &'a str, label: &'a str, required: bool, values: Option<Vec<&str>>, choices: &'a [(&'a str, &'a str)], constraints: Vec<Constraint<'a>>, attributes: Vec<Attr<'a>>, ) -> Result<Self, FormError>

Create an field of any type. This is similar to Field::new(), but some checks and conversions are performed. Returns self, so calls can be chained.

Trait Implementations§

Source§

impl<'a> Debug for HtmlForm<'a>

Source§

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

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

impl<'a> Serialize for HtmlForm<'a>

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<'a> Freeze for HtmlForm<'a>

§

impl<'a> !RefUnwindSafe for HtmlForm<'a>

§

impl<'a> !Send for HtmlForm<'a>

§

impl<'a> !Sync for HtmlForm<'a>

§

impl<'a> Unpin for HtmlForm<'a>

§

impl<'a> !UnwindSafe for HtmlForm<'a>

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, 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.