Validate Date format using jQuery
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(); } }); });
Also read, Validate Date using jQuery
Feel free to contact me for any help related to jQuery, I will gladly help you.