Parsing optional string form values as f64

I have a POST route that receives an HTML form submission. Since HTML form values come through as strings, I'm looking for a clean way to parse an optional field into an f64.

Here's my current setup:

#[derive(Deserialize)]
pub struct Example {
    salary: Option<f64>
}

Router::new().route("/post", post(create));

async fn create(Form(data): Form<Example>) -> impl IntoResponse {
    // handler logic
}

The salary field is optional (not required in the form). My struct may have multiple float fields, and eventually I'll need to save this data to a database. What's the idiomatic way to handle this? Should I accept Option<String> fields and parse them manually into the appropriate types, or is there a better approach that handles parsing and validation more elegantly?

Thank you!

You can use #[serde(deserialize_with = "my_helper_function")] to customize deserialization of a single field, such as for this case, deserializing to Cow<str> and then either parsing as f64 or returning None if the string is empty.

1 Like