Trying to make use of Fluent Validation to ensure that a date range is always filled and that the end date does not occur before the beginning date.
I have the first part done correctly, and it fires correctly, but the second part seems to be unimplementable.
My code:
public class Report1ToExcelValidator : AbstractValidator<Report1ToExcelViewModel> {
public Report1ToExcelValidator() {
RuleFor(x => x.Report1ToExcelDateFrom)
.NotEmpty().WithMessage("Please provide a valid beginning date for the range.");
RuleFor(x => x.Report1ToExcelDateTo)
.NotEmpty().WithMessage("Please provide a valid end date for the range.")
.GreaterThan(x => x.Report1ToExcelDateFrom.Value).WithMessage("The Date To must be after the Date From");
}
}
Where everything gets tripped up is with the .GreaterThan
, which reports an error:
'DateTime' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'DateTime' could be found
My DateTime is not nullable, both DateTimes require content. When I allow Intellisense to bring up possible options, anything after the field name is restricted to things like .Date
and .Hour
, which also do not work. .Value
does not exist in that list of options, neither does .HasValue
.
Really confused on this one.
Also, another question: how do I do separate validations on multiple forms that exist on a single page? Right now I have only the one form, but the form's model is being brought in directly. I cannot seem to figure out how to abstract away the form's model so that I can have more than one model on a page. No data is being brought in.
Right now I have just tried to alter the models to:
public class ReportViewModel {
public Report1ToExcelViewModel Report1ToExcelViewModel { get; set; }
}
[Validator(typeof(Report1ToExcelValidator))]
public class Report1ToExcelViewModel {
public Guid? Report1ToExcelRegion { get; set; }
public DateTime Report1ToExcelDateFrom { get; set; }
public DateTime Report1ToExcelDateTo { get; set; }
}
with the page referencing @model CCS.Models.ReportViewModel
instead of @model CCS.Models.Report1ToExcelViewModel
but I cannot seem to get the page to pull in the Report1ToExcelViewModel so that the form fields get recognized. Right now they error out because 'ReportViewModel' does not contain a definition for [fieldname]
even though I am bringing the Report1ToExcelViewModel
directly into ReportViewModel
as above.
Use
.GreaterThan(x => x.Report1ToExcelDateFrom)
in place of
.GreaterThan(x => x.Report1ToExcelDateFrom.Value)
since your model Report1ToExcelDateFrom is not a nullable Datetime
public DateTime ? Report1ToExcelDateFrom { get; set; }
would have worked out perfectly
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.