title: MVC validating the custom functionality before FormMethod.Post
body: <p>My MVC view is as follows</p>
  
  <p><code>@using (Html.BeginForm("Apply", "Leave", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))</code></p>
  
  <p>Any when user submits the form I am calling another validation function</p>
  
  <pre><code>[HttpPost]
  [AllowAnonymous]
  [ValidateAntiForgeryToken]
  public ActionResult Apply(LeaveViewModel model)
  {
     if (ModelState.IsValid &amp;&amp; ValidateLeave(DateTime.ParseExact(model.FromDate, "MM/dd/yyyy", CultureInfo.InvariantCulture), DateTime.ParseExact(model.ToDate, "MM/dd/yyyy", CultureInfo.InvariantCulture)))
     {
          Leave_Data leaveData = new Leave_Data();
          leaveData.Applied_Date = DateTime.Now;
          leaveData.Employee_Id = 1;
          leaveData.Start_Date = DateTime.ParseExact(model.FromDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
          leaveData.End_Date = DateTime.ParseExact(model.ToDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
          leaveData.Leave_Purpose = model.Reason;
          leaveData.Leave_Type_Id = model.LeaveTypeId;
          leaveData.No_Of_Days = model.Days;
          leaveData.Status_Id = 3;
          db.Leave_Data.Add(leaveData);
          db.SaveChanges();
          model = new LeaveViewModel();
          model = GetCommon(model);
          TempData["Result"] = "Success";
     }
      if (!string.IsNullOrWhiteSpace(TempData["Result"].ToString()))
           return RedirectToAction("ApplyLeave");
       else
          return View();
          }
  
    public bool ValidateLeave(DateTime StartDate, DateTime EndDate)
    {
       using (LeaveEntities entities = new LeaveEntities())
       {
          var appliedDate = entities.Leave_Data.Where(s =&gt; s.Start_Date &gt;= StartDate &amp;&amp; s.End_Date &lt;= EndDate);
          if (appliedDate.Count() &gt; 0)
          {
             TempData["Result"] = "Availed";
             return false;
           }
       }
       return true;
     }
  </code></pre>
  
  <p>I would like to validate this <code>ValidateLeave()</code> before submitting the form so that if it is true only I will proceed else user needs to modify his dates</p>