gpt4 book ai didi

asp.net-mvc-3 - FluentValidation-跨多个属性进行验证

转载 作者:行者123 更新时间:2023-12-03 08:54:57 24 4
gpt4 key购买 nike

具有用户可以输入事件的开始日期/时间和结束日期/时间的表单。到目前为止,这里是验证器:

public class EventModelValidator : AbstractValidator<EventViewModel>
{
public EventModelValidator()
{
RuleFor(x => x.StartDate)
.NotEmpty().WithMessage("Date is required!")
.Must(BeAValidDate).WithMessage("Invalid date");
RuleFor(x => x.StartTime)
.NotEmpty().WithMessage("Start time is required!")
.Must(BeAValidTime).WithMessage("Invalid Start time");
RuleFor(x => x.EndTime)
.NotEmpty().WithMessage("End time is required!")
.Must(BeAValidTime).WithMessage("Invalid End time");
RuleFor(x => x.Title).NotEmpty().WithMessage("A title is required!");
}


private bool BeAValidDate(string value)
{
DateTime date;
return DateTime.TryParse(value, out date);
}

private bool BeAValidTime(string value)
{
DateTimeOffset offset;
return DateTimeOffset.TryParse(value, out offset);
}

}

现在,我还要添加对EndDateTime> StartDateTime(合并的Date + Time属性)的验证,但是不确定如何执行。

编辑:
为了澄清,我需要以某种方式组合EndDate + EndTime / StartDate + StartTime,即DateTime.Parse(src.StartDate +“” + src.StartTime),然后验证EndDateTime与StartDateTime-我该怎么做?

最佳答案

在我重新阅读documentation之后,终于使它工作了:“请注意,Must还有一个额外的重载,它也接受正在验证的父对象的实例。”

public class EventModelValidator : AbstractValidator<EventViewModel>
{
public EventModelValidator()
{
RuleFor(x => x.StartDate)
.NotEmpty().WithMessage("Date is required!")
.Must(BeAValidDate).WithMessage("Invalid date");
RuleFor(x => x.StartTime)
.NotEmpty().WithMessage("Start time is required!")
.Must(BeAValidTime).WithMessage("Invalid Start time");
RuleFor(x => x.EndTime)
.NotEmpty().WithMessage("End time is required!")
.Must(BeAValidTime).WithMessage("Invalid End time")
// new
.Must(BeGreaterThan).WithMessage("End time needs to be greater than start time");
RuleFor(x => x.Title).NotEmpty().WithMessage("A title is required!");
}


private bool BeAValidDate(string value)
{
DateTime date;
return DateTime.TryParse(value, out date);
}

private bool BeAValidTime(string value)
{
DateTimeOffset offset;
return DateTimeOffset.TryParse(value, out offset);
}
// new
private bool BeGreaterThan(EventViewModel instance, string endTime)
{
DateTime start = DateTime.Parse(instance.StartDate + " " + instance.StartTime);
DateTime end = DateTime.Parse(instance.EndDate + " " + instance.EndTime);
return (DateTime.Compare(start, end) <= 0);
}
}

可能有一种更清洁/更简洁的方法来执行此操作,但是到目前为止,它仍然有效。

关于asp.net-mvc-3 - FluentValidation-跨多个属性进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7701612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com