日期时间的 FluentValidation

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

我有以下代码行用于 PublishedDateTime 字段上的数据注释验证,但我想通过 FluentValidation API 进行验证

public Instant Published { get; set; }

[Obsolete("EF-serialization purposes")]
[DataType(DataType.DateTime)]         
[EditorBrowsable(EditorBrowsableState.Never)] 
public DateTime PublishedDateTime
{
  get => Published.ToDateTimeUtc();           
  set => Published = DateTime.SpecifyKind(value, DateTimeKind.Utc).ToInstant();
}

如何将其转换为 FluentValidation?

asp.net data-annotations nodatime fluentvalidation-2.0
1个回答
0
投票

您的问题不清楚,但是当您想验证日期时间字段时,您可以这样做:

RuleFor(s => s.PublishedDateTime)
.NotNull()
.NotEmpty()
.WithMessage("PublishedDateTime is not a valid date.");

如果你的字段是字符串,你可以像这样:

RuleFor(s => s.PublishedDateTime)
    .Must(IsValid)
    .WithMessage("PublishedDateTime is not valid!");

private bool IsValid(string value)
{
    DateTime date;
    return DateTime.TryParse(value, out date);
}
© www.soinside.com 2019 - 2024. All rights reserved.