Keats / validator

Simple validation for Rust structs
MIT License
1.97k stars 141 forks source link

How to get the FIRST validation error? #286

Open jmjoy opened 7 months ago

jmjoy commented 7 months ago

I found that I couldn't get the first validation error.

For example , this is my input:

#[derive(Debug, Deserialize, Validate)]
pub struct CreateInput {
    #[validate(length(min = 1, max = 32))]
    key: String,

    #[validate(length(min = 1, max = 32))]
    display_name: String,

    #[validate(length(min = 1, max = 32))]
    parent_key: Option<String>,
}

I want to get the first error message when validate failed (if field key validated failed, then return the error of field key, otherwise display_name, and otherwise parent_key) :

let message = err /* ValidationErrors */
    .field_errors()
    .iter()
    .next()
    .and_then(|(_, es)| es.iter().next())
    .map(|e| e.to_string())
    .unwrap_or_else(|| "unknown validation error".to_string());

But unfortunately, field_errors returns HashMap which is unordered, when the input has multiple field validation errors, the error message will be random.

One idea I have is to add a feature order and replace HashMap with IndexMap.

bharath-rl commented 7 months ago

@jmjoy have you found the answer ? because the errors are in random order for me

jmjoy commented 7 months ago

@jmjoy have you found the answer ? because the errors are in random order for me

I have already stated the answer in the description.

799189288 commented 2 months ago

@jmjoy have you found the answer ? because the errors are in random order for me

I have already stated the answer in the description. so how to get first error

jmjoy commented 2 months ago

so how to get first error

A PR needs to be submitted to modify the behavior of fields_errors.