1

Given the following codes:

My razor code is this one:

<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
     <tr>
        <td>Date: </td>
        <td>
            <div class="form-group input-group-sm">
                @Html.LabelFor(model => model.StartDate)
                @Html.TextBoxFor(model => model.StartDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
                @Html.ValidationMessageFor(model => model.StartDate)
            </div>
        </td>
    </tr>

    <tr>
        <td>end date: </td>
        <td>
            <div class="form-group input-group-sm">
                @Html.LabelFor(model => model.EndDate)
                @Html.TextBoxFor(model => model.EndDate, new { @class = "form-control datepicker", placeholder = "Enter Drop-off date here..." })
                @Html.ValidationMessageFor(model => model.EndDate)
            </div>
        </td>
    </tr>
 </table>
 }

My model is this one:

public class MyModel
{
    [Display(Name = "From")]
    [Required]
    public DateTime StartDate { get; set; }

    [Display(Name = "To")]
    [Required]
    public DateTime EndDate { get; set; }

}

Could you advice me a way to check if the StartDate is lower than EndDate? Thank you

Karim Bhatti
  • 13
  • 1
  • 3
  • please check this: https://stackoverflow.com/questions/9371550/asp-net-mvc-validation-on-2-fields-one-must-exist-if-other-entered and implement `IValidatableObject` in your model eg. ```public IEnumerable Validate(ValidationContext validationContext) { if (StartDate > EndDate) yield return new ValidationResult("End date must be after start date"); }``` – Greg Apr 27 '19 at 16:39

1 Answers1

0

use this one I hope useful:

  @if (Model.StartDate < Model.EndDate )
  {
      //Do something
  }
hassan.ef
  • 1,300
  • 2
  • 11
  • 19