Skip to content

Instantly share code, notes, and snippets.

@rebo
Created July 23, 2020 09:54
Show Gist options
  • Save rebo/d178592a3aaa6c146e62af1ca70a09e2 to your computer and use it in GitHub Desktop.
Save rebo/d178592a3aaa6c146e62af1ca70a09e2 to your computer and use it in GitHub Desktop.
#[derive(Debug, Default, Validate, Deserialize,Clone)]
struct SignupData {
#[validate(email)]
mail: String,
#[validate(phone)]
phone: String,
#[validate(url)]
site: String,
#[validate(length(min = 1), custom = "validate_unique_username")]
#[serde(rename = "firstName")]
first_name: String,
#[validate(range(min = 18, max = 20))]
age: u32,
}
fn validate_unique_username(username: &str) -> Result<(), ValidationError> {
if username == "xXxShad0wxXx" {
// the value of the username will automatically be added later
return Err(ValidationError::new("terrible_username"));
}
Ok(())
}
#[atom]
fn signup_data() -> Atom<SignupData> {
SignupData::default()
}
#[reaction]
fn client_validation() -> Reaction<Result<(), ValidationErrors>> {
signup_data().observe().validate()
}
#[reaction]
fn server_validation() -> Reaction<Option<Result<(), ValidationErrors>>> {
if let Ok(_) = client_validation().observe() {
//validate_with_server(signup_data().get());
Some(Ok(()))
} else {
None
}
}
#[reaction]
fn form_widget() -> Reaction<Node<Msg>> {
let form_data = signup_data().observe();
let client_errors = client_validation().observe();
let server_errors = server_validation().observe();
div![
form![
s().style_child("input").b_width(px(1)).b_color("gray").b_style_solid().display_block(),
label!["Mail"],
input![attrs![At::Value => form_data.mail ], signup_data().input_ev(Ev::Input,|data,inp| data.mail = inp)],
label!["Phone"],
input![attrs![At::Value => form_data.phone ], signup_data().input_ev(Ev::Input,|data,inp| data.phone = inp)],
label!["Site"],
input![attrs![At::Value => form_data.site ], signup_data().input_ev(Ev::Input,|data,inp| data.site = inp)],
label!["First Name"],
input![attrs![At::Value => form_data.first_name ], signup_data().input_ev(Ev::Input,|data,inp| data.first_name = inp)],
label!["Age"],
input![attrs![At::Value => form_data.age ], signup_data().input_ev(Ev::Input,|data,inp| data.age = inp.parse::<u32>().unwrap())],
],
h1!["Client Errors: "],
match client_errors {
Ok(_) => span!["None"],
Err(err) => pre![format!("{:#?}",err)],
},
match server_errors {
Some(Ok(_)) => span!["None"],
Some(Err(err)) => pre![format!("{:#?}",err)],
None => pre!["Not checked by server yet,because client didnt pass"],
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment