invalid required show in swagger
aminmansouri2000 opened this issue · 1 comments
aminmansouri2000 commented
Hello
I have a Date Range Model with start and end property. also I have Validator for Date Range Model to set property NotEmpty().
If I Use DateRangeModel in another class twice, and only one of them use validator swagger show two property as required,
but optional property must not be required (highlighted in picture), because no date range validator set for it in request class.
the code are in blow
public class DateRangeModel
{
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
}
public class DateRangeValidator : AbstractValidator<DateRangeModel>
{
public DateRangeValidator()
{
RuleFor(obj => obj.StartDate)
.NotEmpty();
RuleFor(obj => obj.EndDate)
.NotEmpty();
RuleFor(obj => obj.StartDate)
.LessThanOrEqualTo(obj => obj.EndDate);
}
}
public class TestRequest
{
/// <summary>
/// this is mandatory date range
/// </summary>
public DateRangeModel MandatoryDateRange { get; set; }
/// <summary>
/// this is optional date range
/// </summary>
public DateRangeModel OptionalDateRange { get; set; }
}
public class TestRequestValidator : AbstractValidator<TestRequest>
{
public TestRequestValidator(DateRangeValidator dateRangeValidator)
{
// date range validator set to only one property
RuleFor(obj => obj.MandatoryDateRange)
.NotEmpty()
.SetValidator(dateRangeValidator);
}
}
[ApiController]
[Route("[controller]")]
public class MicroELementController : ControllerBase
{
[HttpPost(Name = "test-micro-elemeny")]
public string Get(TestRequest request)
{
return "success";
}
}
Thank you
petriashev commented
Hello
Validator is paired to type it validates. So SetValidator is not necessary (validators are registered in startup).
You can create two types: with required and with optional fields