Feature Request - Display multiple error messages for a field one at a time
waelsaad opened this issue · 4 comments
Hi,
This is a great library by the way but I am just trying to work out the following, consider the following validation
lazy var firstNameValidation: ValidationContainer = {
let validators: [StringValidator] = [
PrefixValidator(prefix: "mr."),
CountValidator(count: 6, type: .greaterThanOrEquals)
]
return $firstName.allValid(validators: validators, form: form)
}()
Based on the sequence of the validation in the array. We should display the error message that is associated with the PrefixValidator first, then if it is satisfied we should then display the error message of the second CountValidator.
At the moment the implementation of func allValid(
is setting the error message to be only the required one.
errorMessage: errorMessage().orIfEmpty(form.messages.required),
I think for allValid we should let it workout which error message needs to be displayed. To be honest I tried to modify the public static func create( which is relevant to allValid to set the error message dynamically as we are looping thru the validators but it was slightly tricky.
If there is a simpler way that I am not aware of to do display multiple error messages for the one field (1 at a time) please shed some light.
Thank you.
Consider validating a required file to be uploaded:-
Two validators are required, the first ensures there is a value and the second ensures the file size is correct
[NonEmptyValidator(), FileSizeValidator()]
We need to display an error message for the first validator if there is no value but if there is a file that has been selected but above 1MB then we display a different error message.
Thanks.
I have implemented a solution, perhaps not the best but it works none the less:-
1- Kept everything as it is.
2- Created additional func validate(value: String?, validators: [StringValidator]) -> Validation {
within CompositeValidator
3- Created additional static func create(
inside ValidationPublishers
based on the last static func create(
4- I add only the validators that are failing as follows:
validators.forEach { if $0.validate().isFailure { form.append(ValidatorContainer(id: id, validator: $0, disableValidation: disableValidation)) } }
Hi Wael,
Many thanks for your contribution and great ideas.
Could you kindly submit a PR with that change and I'll review it and merge to the main branch.
I think we should have a strategy for the composite validator. My initial thoughts is to have and enum with 2 cases:
enum CompositeValidationStrategy {
case all
case firstInvalid
}
firstInvalid
means we will validate the validators sequentially and once we find an invalid one, we break and show the message.
What do. you think?
Hi Wael,
We're thrilled to announce that version 1.0.0 of our library is now available, featuring the ability to specify different error messages for each validator included in a CompositeValidator.
Many thanks for your feedback