Search code examples
javascriptjqueryhtmlmaskmasking

j Query masking for multiple formats (Optional digits)


I am trying to mask CVV card..!

it should allow 3 or 4 numbers xxx 123 or xxxx 4567

I have tried like this but it is allowing only 4 characters, how can I allow both formats with jquery mask plugin

$("#card_cvv").mask("9999"); //it is accepting 4 charecters

$("#card_cvv").mask("999"); //it is accepting 3 charecters

i want some thing like this combination: $("#card_cvv").mask("999 or 9999");

HTML:

<input id="card_cvv" name="ccv" data-toggle="tooltip" required="" value="" class="form-control alt card_cvv" type="text" placeholder="CCV" aria-required="true">

Plug in: https://igorescobar.github.io/jQuery-Mask-Plugin/


Solution

  • You must use 0 for the required digits and 9 for the optional

    $("#card_cvv").mask("0009",{ 
      clearIfNotMatch: true 
    });
    
    $('button').on('click', function(){
        console.log( $('#card_cvv').cleanVal() );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.12/jquery.mask.min.js"></script>
    
    <input type="text" id="card_cvv">
    
    <button>log clear value</button>