Open kingua opened 1 year ago
I think I figured this out:
public class AttachmentUploadValidator : AbstractValidator<AttachmentUpload>
{
public AttachmentUploadValidator()
{
RuleLevelCascadeMode = CascadeMode.Stop;
RuleSet(ValidatorRuleSets.ClientRules, () =>
{
RuleFor(attachment => attachment.AttachmentType)
.NotEmpty()
.When(attachment => MimeType.EquipmentInformation.ContainsValue(attachment.ContentType));
RuleFor(attachment => attachment.FileContent).NotEmpty()
.WithMessage("'File' must be selected");
});
}
}
**public class AttachmentUploadListValidator : AbstractValidator<List<AttachmentUpload>>
{
public AttachmentUploadListValidator()
{
RuleForEach(x => x).SetValidator(new AttachmentUploadValidator());
}
}**
The above seems to properly validate, but now I don't get the actual validation error message returned as validationResult is just a bool. Is there a way to get the error messages so I can do something like the following?
foreach (var attachment in Model)
{
var validationResult = await FluentValidationValidator!.ValidateAsync(strategy =>
strategy.IncludeRuleSets(ValidatorRuleSets.ClientRules));
if (validationResult)
{
numberOfValidAttachments++;
}
else
{
var errorMessages = string.Join(", ", validationResult.Errors.Select(e => e.ErrorMessage));
validationMessages.Add($"Attachment: {attachment.FileName} is invalid for the following reasons: {errorMessages}.");
}
}
I'm trying to loop through and validate a collection of objects, but I'm getting the following error. It seems that the validator doesn't have the context of the object to validate. What am I doing wrong / how can I accomplish this?
System.InvalidOperationException: No pending ValidationResult found
Here is the component markup:
Below is the codebehind in its entirety for context, but the relevant method is UploadEquipmentAttachments():