Closed MagnusHJensen closed 1 year ago
The library avoids giving error messages since it would mean adding i18n to them which I'd rather not do here.
What is the approach for giving proper validation errors? I don't want to do duplicate validation, just to give a proper message. Is there an identifier for each type of fail that can be parsed?
You can write custom messages by handling the output of the validate: https://docs.rs/validator/latest/validator/struct.ValidationErrors.html. You will get the code for the validator as well as all the params that are set (+the value). See https://github.com/Keats/validator/blob/master/validator_derive_tests/tests/length.rs#L75-L93 for an example of the output of a failing length
test.
That still requires me to do my own validation (doing exactly the same validation this lib does) just to provide an understandable error message.
#[derive(Debug, Validate)]
struct TestStruct {
#[validate(length(min = 5, max = 10))]
val: String,
}
let s = TestStruct { val: String::new() };
let res = s.validate();
let err = res.unwrap_err();
let errs = err.field_errors();
if errs["val"][0].params["min"] > errs["val"][0].params["value"] {
return "Oh no your string is shorter than the required";
}
So now I just implemented a length validation.
You do get the code, but nothing more. Just length
so you don't know if it's too short, or too long.
Yep but that's better than having baked errors in English and having to pattern match strings to get the issue.
You can use the custom
for now and pass the message
directly. In a future rewrite, we could/should allow for validator specific callables (eg for the length
validator, we could have min_message
, max_message
, equal_message
and interval_message
that are functions returning a Cow<static, str>
) but I'm not sure if it's worth it since it's only for range
and length
really.
We'll have to disagree. "English messages" > "No message" Anyways, feel free to close this suggestion if it will never happen.
Currently if a validation for length fails, it just gives the error:
length
It would be nice if it failed on min requirement, that it saidlength was less than {min}
, and if it failed on max that it said:length was greater than {max}