javascriptjqueryjquery-mask

Mask Text Input to Validate MM/YY jquery-mask-plugin


Using jquery-mask-plugin I want to mask an input to only accept reasonable MM/YY

$('#expDate').mask("99/99"); works but it allows for 55/66 which is not an acceptable month.

How can I make it so the first part of the mask is <= 12


Solution

  • You cannot do this with just the jquery-mask plugin. As you noted, it only masks out certain TYPES of inputs, such as numbers (in general), letters, symbols, etc. It does not perform data validation (which is what you're asking for.

    You can write a simple jQuery function that runs onblur, etc that rejects invalid combinations:

    $('#expDate').blur(function() {
      let val = $(this).val();
      if (val.indexOf('/') > 0)
        {
          let first = val.split('/')[0]; 
          if (first > 12)  $(this).val('');
        }   
    });
    

    Alternatively, you can use the great jQuery Validate plugin: https://jqueryvalidation.org/

    To be clear, you want data validation beyond just basic input masking.