Search code examples
javascriptjquery

Masking a social security number input


For a web application I'm building privacy is very important and so is the format users input their data.

To help with this I have inserted a jquery library that will help mask the fields http://igorescobar.github.io/jQuery-Mask-Plugin/

However, I seem to be having trouble masking social security numbers. For instance, the format is coming through nicely 567-78-7890, but I can't seem to figure out how to mask or hide those first four numbers... like *--7890.

My html is just an input field

<input class='social' />

and with this plugin I have tried masking it as

$('.social').mask('000-00-0000');

This is just providing formatting

$('.newsocial').mask('xxx-xx-0000');

This will just replace the numbers they have entered with x's.

I have also set up a jsFiddle to help http://jsfiddle.net/w2sccqwy/1/

Any help would be wonderful!

P.S. I cannot use a password field because the last four numbers have to be shown to the user and I cannot have more than one field. This is a company requirement. I cannot change a company requirement as much as I want to.


Solution

  • For anyone who might run into this in the future I was able to figure out a solution that will mask any kind of field and format it without messing with any other plugin.

    In the html you would need two inputs

    <input class='number' />
    <input class='value' />
    

    and then position the number field over the value

    and then in your javascript

     $('.value').on('keydown keyup mousedown mouseup', function() {
         var res = this.value, //grabs the value
             len = res.length, //grabs the length
             max = 9, //sets a max chars
             stars = len>0?len>1?len>2?len>3?len>4?'XXX-XX-':'XXX-X':'XXX-':'XX':'X':'', //this provides the masking and formatting
            result = stars+res.substring(5); //this is the result
         $(this).attr('maxlength', max); //setting the max length
        $(".number").val(result); //spits the value into the input
    });
    

    And a jsFiddle for those who would like to see the result. http://jsfiddle.net/gtom9tvL/