Date Validation in ASP.Net Webforms

  • Tuesday, June 17, 2014 8:30 PM EST
  • Last Edited: Tuesday, June 17, 2014 8:47 PM EST

For validating dates in ASP.Net Webforms, the fastest way of checking a date entered if valid or not would be to create a Date object out of the string. If the object creation is successful, it would mean the date is valid otherwise it will be an invalid date.

Using AJAX to validate input date w/  custom validator:

<asp:CustomValidatorID="valEndVacDate"runat="server"ErrorMessage="*Invalid Date"CssClass="errormessage"ClientValidationFunction="validateDate"ControlToValidate="txtEndDate"Display="Dynamic"></asp:CustomValidator>

 

//corresponding jquery calling server  function/method

function validateDate(source, e) {

   var dateID = "#" + source.controltovalidate;

    $.ajax({

       type: "POST",

       url: "/Services.asmx/ValidateDate",

       data: "{'date':'" + $(dateID).val() + "'}",

       contentType: "application/json; charset=utf-8",

       dataType: "json",

       async: false,

       success: function (response) {

          e.IsValid = response.d;

       }

    });

   return;

}

 

//corresponding server function/method

 

[WebMethod]

publicbool ValidateDate(string date)

{

   try

    {

       string[] myDate = newstring[3];

        myDate = date.Split('-');

       //yyyy-mm-dd format 

       DateTime startdate = newDateTime(Convert.ToInt32(myDate[0]), Convert.ToInt32(myDate[1]), Convert.ToInt32(myDate[2]));

 

       returntrue;

     }

    catch (Exception ex)

     {

       returnfalse;

        

     }

}

 

comments powered by Disqus