Trait rocket::request::FromFormValue [] [src]

pub trait FromFormValue<'v>: Sized {
    type Error;
    fn from_form_value(form_value: &'v str) -> Result<Self, Self::Error>;

    fn default() -> Option<Self> { ... }
}

Trait to create instance of some type from a form value; expected from field types in structs deriving FromForm.

Examples

This trait is generally implemented when verifying form inputs. For example, if you'd like to verify that some user is over some age in a form, then you might define a new type and implement FromFormValue as follows:

use rocket::request::FromFormValue;
use rocket::Error;

struct AdultAge(usize);

impl<'v> FromFormValue<'v> for AdultAge {
    type Error = &'v str;

    fn from_form_value(form_value: &'v str) -> Result<AdultAge, &'v str> {
        match usize::from_form_value(form_value) {
            Ok(age) if age >= 21 => Ok(AdultAge(age)),
            _ => Err(form_value),
        }
    }
}

This type can then be used in a FromForm struct as follows:

#[derive(FromForm)]
struct User {
    age: AdultAge,
    ...
}

Associated Types

The associated error which can be returned from parsing. It is a good idea to have the return type be or contain an &'v str so that the unparseable string can be examined after a bad parse.

Required Methods

Parses an instance of Self from an HTTP form field value or returns an Error if one cannot be parsed.

Provided Methods

Returns a default value to be used when the form field does not exist. If this returns None, then the field is required. Otherwise, this should return Some(default_value). The default implementation simply returns None.

Implementors