Search code examples
javascriptjquerymasking

Restriction to follow mm/dd/yyyy in jquery masking?


i am using jquery masking in my project to allow the date in mm/dd/yyyy like below

<script src="Scripts/jquery.maskedinput-1.2.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {

        //Input Mask for date of birth or date in general
        $("#txtDOB").mask("99/99/9999");

    });
</script>

But at present user can enter any value greater than 12 and 0 for month. Similarly for days greater than 31 . Is there a way i can restrict so that user can't type more than 12 or 0 for mm . similarly he can type more than 31 or 0 for days ?

i have java script validation in place at submit but is there a way to restrict while type ?


Solution

  • try with this:

    $("#txtDOB").mask('d/m/y', {'translation': {
        d: {pattern: /[0-2]?\d|3[0-1]/}, 
        m: {pattern: /0[1-9]|1[0-2]/},  
        y: {pattern: /[1-2]\d{3}/}
      }
    });
    

    UPDATED

    the mask has three parts, dfor days, mfor months and y for years (you can switch the order if you want), and I have made 3 regex, one for each.

    • d pattern: there are two posible matches (two options) separated by |

      • first one [0-2]?\d first digit should be 0 up to 2([0-2]) and its optional (?) the second digit could be 0-9 (\d)
      • second one 3[0-1] first digit is 3 and the second one only can be 0 or 1
    • m pattern: there are two options separated by |

      • first one 0[1-9], if month start by 0 the second digit could be 1 to 9
      • second one 1[0-2], if month start by 1the second digit only coudl be 0 to 2
    • ypattern [1-2]\d{3}: first digit can be 1 or 2 and then should be 3 digits [0-9].