FV When causes swagger to not be updated.
niemyjski opened this issue · 3 comments
I'm using the latest beta version on .NET 7 latest with the latest stable FV. I have the following record and validation rule and I noticed that my swagger doesn't include any of the not empty or length data (I was expecting these to be populated along side the nullable flag to control if they are optional):
public record MyModel(string? InviteToken = null);
public class MyModelValidator : AbstractValidator<MyModel>
{
public MyModelValidator ()
{
RuleFor(u => u.InviteToken).NotEmpty().Length(40).When(m => m.InviteToken is not null);
}
}
Looking at the generated swagger.json
"MyModel": {
"required": [
],
"type": "object",
"properties": {
"invite_token": {
"type": "string",
"nullable": true
}
},
"additionalProperties": false
},
Hi!
Conditional rules skips by default.
What schema do you expect?
It's tricky because we have a condition in the When. But I'd expect this case to behave like Optional when not empty, otherwise the length has to be 40. Seems like FV needs a WhenNotEmpty
In data Annotations, I'd do
[StringLength(40, MinimumLength = 40)]
public string? InviteToken { get; init; }
And it would not mark it as required but would add length rules. Which would mean optional when null, otherwise must be 40 characters long.
@niemyjski you could avoid the when because FluentValidation does not enter into a rule if the property is null. So the best thing you can do is to change the removing the NotEmpty rule, only there is a weird condition that is if the string has 40 whiteSpaces the Rule will not apply the same result, for this you could apply another rule making a workAround.I have kind of the same problem but when IsNullOrEmpty or IsNullOrWhiteSpace for strings, but I do not find a workAround to this matter
But if I remove the when operator the behavior of the validator changes it would be nice if there is a When with isNullOrEmpty/IsNullOrWhiteSpace the package continues reading the Rule and apply the documentation.
I have seen through the solution if there was a way to get the condition applied on the Where clause and there is no way right now because the library gets the info of the rule from IRuleComponent that is the element of FluentValidation that exposes the info and I see that there is only a exposure of the properties HasCondition or HasAsyncCondition
There is an issue on FluentValidation where they request Jeremy to add the identification of the when conditions, FluentValidation/FluentValidation#2114