在我的 ASP.NET Core-6 Web API 中,我得到了一个请求正文以使用 Fluent Validation 进行验证,然后传递到第三方 API。这是请求正文。
请求正文:
{
"end_date": "2019-08-24T14:15:22Z",
"employee_code": "emp242ac120002",
"start_date": "2019-08-24T14:15:22Z"
}
员工历史请求:
public class EmployeeHistoryRequest
{
public string employee_code { get; set; }
public DateTime start_date { get; set; }
public DateTime end_date { get; set; }
}
EmployeeHistoryRequestValidator:
public class EmployeeHistoryRequestValidator : AbstractValidator<EmployeeHistoryRequest>
{
public EmployeeHistoryRequestValidator()
{
RuleFor(p => p.employee_code)
.NotNull().WithMessage("Employee Code cannot be null")
.NotEmpty().WithMessage("Employee Code field is required. ERROR!");
RuleFor(p => p.start_date)
.NotNull().WithMessage("Start Date cannot be null")
.NotEmpty().WithMessage("Start Date should not be empty. ERROR!");
RuleFor(p => p.end_date)
.NotNull().WithMessage("End Date cannot be null")
.NotEmpty().WithMessage("End Date should not be empty. ERROR!");
RuleFor(x => x).Must(x => x.end_date == default(DateTime) || x.start_date == default(DateTime) || x.end_date > x.start_date)
.WithMessage("End Date must be greater than Start Date");
}
}
这里我比较的是开始日期和结束日期。
使用 Fluent Validation,我如何验证每个日期(开始日期和结束日期)必须采用以下格式:yyyy-MM-dd?
Yoc 可以使用比较正则表达式并返回结果的自定义方法来匹配日期格式。 试试下面
RuleFor(x => x.InputDate).Must(MatchDateFormat);
private bool MatchDateFormat(DateTime date)
{
return Regex.IsMatch(date.ToString(), @"^\d{4}-\d{2}-\d{2}$");
}