Function to validate Date of Birth using Regex

Regex to validate date of birth

Solution

In Jquery

var checkDOB = function () {   
debugger;
   var regexp = new RegExp( '^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|20)\\d\\d$');
   var check = $("#AddDateOfBirth").val();
   if (!regexp.test(check)) {

       alert('Invalid Format. Please Enter: dd/mm/yyyy');
       $('#AddDateOfBirth').css('border-color', 'red');
       return false;

   }
   else {
       $('#AddDateOfBirth').css('border-color', 'green');
       return true;
   }
}

In HTML

@Html.TextBox("AddDateOfBirth", null, new { @class = "form-control text-box", @placeholder = "dd/mm/yyyy", @onchange = "checkDOB()" })

EXPLANATION

This regex will validate date of birth by allowing you to enter the date of birth in this format dd/mm/yyyy only. Invalid input (not in the format dd/mm/yyyy) will return false and make the borders of text-box red.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a free website or blog at WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started