Validate Date format using jQuery

In this post, we will see how can you validate the user's entered input date's format using jQuery. For demo, I have used "mm/dd/yyyy" or "mm-dd-yyyy" format to be considered as valid format. The date format checking is done using regular expression. So first, let's create a function which validate any input value against the regular expression.

function ValidateDate(dtValue)
{
var dtRegex = new RegExp(/bd{1,2}[/-]d{1,2}[/-]d{4}b/);
return dtRegex.test(dtValue);
}

Below is the HTML code. There is a span tag next to the textbox with cssclass="error" which is displayed if the entered date is not valid. By default, it will be hidden.

<span>Enter Date: </span><input type="text" id="txtDate" />
<span class="error"> Invalid Date.(mm/dd/yyyy or mm-dd-yyyy)
</span>
<input id="btnSubmit" type="submit" value="Submit">

CSS class for error message

.error
{
    color: red;
    font-family : Verdana;
    font-size : 8pt;
}

Above ValidateDate() function will check the argument value against this regular expression. If the entered value is in mm/dd/yyyy or mm-dd-yyyy format then this function will return true, otherwise false.

Also read, Validate Date using jQuery

Below jQuery code gets called on click of submit button, which reads the value from the text box and calls the ValidateDate() function. If it is true, then form is submitted and error message is not displayed to the user. Otherwise, error message will appear next to the textbox and user has to correct the value before submitting the form again.

$(document).ready(function() {
$('.error').hide();
$('#btnSubmit').click(function(event){
   var dtVal=$('#txtDate').val();
   if(ValidateDate(dtVal))
   {
      $('.error').hide();
   }
   else
   {
     $('.error').show();
     event.preventDefault();
   }
   });
});
See live Demo and Code.

Also read, Validate Date using jQuery

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...