Blog Image

Validate date format mm/dd/yyyy by using jquery validation library

First add the custom method to the validation library as below. Can you put this code in your jquery validation file or in your page where you want to validate the date, just before setting your validation rule for your form.

$.validator.addMethod(“dateFormat”,
 function (value, element) {
 return value.match(/^(?:(0[1-9]|1[012])[\/.](0[1-9]|[12][0-9]|3[01])[\/.](19|20)[0-9]{2})$/);
 },“Please enter a date in the format mm/dd/yyyy.”);

Now suppose you are using a datepicker or input field to accept the date in mm/dd/yyyy format like 02/21/2018 as example. You can validate it as below;

 

<form id="your-form-id">
<input id="submission_date" name="submission_date" type="text" />
<input type="submit" value="submitForm" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js">
 <script type="text/javascript">

$("#your-form-id").validate({
 rules: {
 submission_date: {
 required: true,
 dateFormat: true,
 },
 },
 messages: {
 submission_date: {
 required: "Please select or enter the submission date!!.",
 dateFormat: "Submission date should in the format mm/dd/yyyy.",
 },
 },
 errorPlacement: function(error, element) {
 error.insertAfter(element);
 },
 submitHandler: function (formName) {
 formName.submit();
 }
 });
 </script>



Author: admin

Vinod Ram has been in Software Industry since 2006 and has experience of over 16 years in Software Development & Project Management domain specialised majorly in LAMP stack & Open Source Technology, building enterprise level Web based Application, Large Database driven and huge traffic Websites and Project Management. He loves to write information articles and blog to share his knowledge and experience with the outside world and help people to find solution for their problems.