如何在 Razor .Net Core 中进行日期验证

How to do Date validation in Razor .Net Core

需要对开始日期和结束日期进行标准验证。应包括:

  1. 结束日期 > 开始日期。
  2. 结束日期 < 今天日期。
  3. 开始日期 < 结束日期

到目前为止尝试了以下方法,但这些方法并不完全有效: https://itecnote.com/tecnote/c-asp-mvc-datetime-range-data-annotation-from-now-to-20-years/

请指教

您可以使用 fluent validation 来实现。我在这里写了一个简单的demo,希望对你有帮助。

演示

 public class Time
    {
        public DateTime Start { get; set; }
        public DateTime End  { get; set; }
    }

日期时间验证器

public class DateTimeValidator : AbstractValidator<Time>
    {
      
        public DateTimeValidator()
        {
            DateTime now = DateTime.Now;

            RuleFor(x => x.Start)
                .LessThan(x => x.End)
                .WithMessage("Start must < End")
                .NotEmpty(); 

            RuleFor(x => x.End)
                .GreaterThan(x => x.Start)
                .WithMessage("End must > Start")
                .NotEmpty();
        }
    }

页数

@model Time

<form asp-action="Time" method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Start" class="control-label" ></label>
                <input asp-for="Start" class="form-control" type="date" max='' id="startDate"/>
                <span asp-validation-for="Start" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="End" class="control-label"></label>
                <input asp-for="End" class="form-control" type="date" max='' id="endDate"/>
                <span asp-validation-for="End" class="text-danger"></span>
            </div>
            <button type="submit">submit</button>
</form>

@section  Scripts{
    <script>
        //I use js to allow users to select only the latest date up to yesterday
        function addZero(n) {
            return parseInt(n) >= 10 ? n.toString() : '0' + n;
        }
        let dateNow = new Date(),
            yearNow = dateNow.getFullYear(),
            monthNow = dateNow.getMonth() + 1,
            dayNow = dateNow.getDate() - 1,
            maxDate = yearNow + '-' + addZero(monthNow) + '-' + addZero(dayNow);
        let inp = document.querySelector('#startDate');
        let inp2 = document.querySelector('#endDate');
        inp.setAttribute('max', maxDate);
        inp2.setAttribute('max',maxDate);

    </script>
}

演示

编辑

[HttpPost]
        public IActionResult Time(Time modeo)
        {
            if (ModelState.IsValid)
            {
                // add your code here.....
                
                
            }
            //return model and error message
           return View(modeo);
        }