2

In my mvc web app, I have a form employees use to submit holiday request. Is there a way for a warning message to be displayed if a date in the past is selected? Something similar to a validation message but I'd still like employees to be able to select dates from the past.

Here is my form in the View:

     @using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal" style=" position:relative; top:20px;border-radius: 0px; border-color: #F47B20; border-style: solid; border-width: 5px; background-repeat: no-repeat; background-position: right; padding: 60px; background-size: contain; background-color:white ">
        <h2 align="center">Holiday Request Form</h2>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">
            @Html.LabelFor(model => model.StartDate, "Start Date", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StartDate, "Start Date", new { htmlAttributes = new { @class = "form-control", autocomplete = "off" } })
                @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FinishDate, "Finish Date", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FinishDate, new { htmlAttributes = new { @class = "form-control", autocomplete = "off" } })
                @Html.ValidationMessageFor(model => model.FinishDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.HoursTaken, "Hours Requested", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.HoursTaken, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.HoursTaken, "", new { @class = "text-danger" })
            </div>
        </div>




        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Submit" class="btn btn-warning" />
            </div>
        </div>
    </div>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")

<script type="text/javascript">

    $(document).ready(function () {
        $('input[type=datetime]').datepicker({
            dateFormat: "dd/M/yy",
            changeMonth: true,
            changeYear: true,
            yearRange: "-70:+70"
        });

    });
</script>

}

Controller:

[Authorize(Roles = "Admin,User,SuperUser")]
    public ActionResult Create()
    {
        ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName");
        return View();

        string name = Session["Name"].ToString();

        var EmployeeIDCatch = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID);

    }

    // POST: HolidayRequestForms/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "RequestID,StartDate,FinishDate,HoursTaken,Comments,YearCreated,MonthCreated,DayCreated,YearOfHoliday,Approved,SubmittedBy,ApprovedBy")] HolidayRequestForm holidayRequestForm)
    {
        if (ModelState.IsValid)
        {

            if (Session["Name"] == null)
            {
                TempData["msg"] = "Your Session Expired - Please Login";
                return RedirectToAction("Login", "Account");
            }

            string name = Session["Name"].ToString();

            var employeeID = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.EmployeeID).FirstOrDefault();
            holidayRequestForm.EmployeeID = employeeID;

            var submittedby = db.Employees.Where(s => s.Email.Equals(name)).Select(s => s.Email).FirstOrDefault();
            holidayRequestForm.SubmittedBy = submittedby;


            db.HolidayRequestForms.Add(holidayRequestForm);
            db.SaveChanges();
            SendMailToAreaManager();
            SendMailToManager();
            SendMailToAdmin();
            return RedirectToAction("Index", "Calendar");
        }

        ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FullName", holidayRequestForm.EmployeeID);
        return View(holidayRequestForm);
    }
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Conor8630
  • 345
  • 1
  • 17
  • Capture the start and end date selection in JQuery then show a pop up on the client if in the past. – Wheels73 Feb 27 '19 at 09:56
  • Just a simple date comparison using if-condition is enough. Depending on the library you're using to show date picker, you can try suggestions on this issue: https://stackoverflow.com/questions/27714469/check-if-date-is-in-the-past-without-submitting-form/27714551. – Tetsuya Yamamoto Feb 27 '19 at 10:02

2 Answers2

4

You can do all of work with jQuery. Here is the code:

HTML:

<input placeholder="dd/mm/yyyy" id="datepicker"/>
<p id="warning" style="color:orange"></p>

jQuery:

 $( function() {
    $( "#datepicker" ).datepicker({
        onSelect: function(date) {
          let dateNow = new Date();
          let dateSelect = new Date(date);
          dateNow.setHours(0,0,0,0);

          if(dateNow > dateSelect){            
            $("#warning").show().text("The date in the past is selected")
          }else{
            $("#warning").hide()
          }
       }
    });
});
  • Great it works!! Could you explain how to implement this with a form field/editorfor? – Conor8630 Feb 27 '19 at 12:05
  • Yes is very simple. Add a paragraph below ValidationMessageFor, like I added in my example above(

    ) and put the jQuery code, that I wrote above, into
    – Afrim Kafexholli Feb 27 '19 at 12:40
  • Okay, perfect. I also have a datepicker(which I've added to the question). Would this be put in a separate function or the same one? – Conor8630 Feb 27 '19 at 12:49
  • You can put in the same function. Just take onSelect and the function(date) after yearRange: "-70:+70". – Afrim Kafexholli Feb 27 '19 at 12:56
  • Yep, Works Perfectly! Thank you – Conor8630 Feb 27 '19 at 13:48
1

You can create an custom attribute for this case.

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class CheckDateAttribute : ValidationAttribute
    {   
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            DateTime date = (DateTime)value;


            if (date > DateTime.Now)
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(ErrorMessage);
            }
        }
    }

And set to your property:

[CheckDate(ErrorMessage = "Date should not past")]
        public string StartDate { get; set; }

If you dont want to change your model class you can do like this

public class EmployeeMetaData
    {

        [CheckDate(ErrorMessage = "Date should not past")]
        public string StartDate { get; set; }
    }

    [MetadataType(typeof(EmployeeMetaData))]
    public partial class Employee
    {

    }
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62