ASP.NET Core Web API - 如何使用流利的验证器验证和格式化 start_date 和 end_date

问题描述 投票:0回答:1

在我的 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

c# asp.net-core fluentvalidation
1个回答
0
投票

Yoc 可以使用比较正则表达式并返回结果的自定义方法来匹配日期格式。 试试下面

RuleFor(x => x.InputDate).Must(MatchDateFormat);
private bool MatchDateFormat(DateTime date)
{
    return Regex.IsMatch(date.ToString(), @"^\d{4}-\d{2}-\d{2}$");
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.