Search code examples
jquerymasking

masking numbers to a special character (*) in input


I am trying to mask all the numbers in SSN field to * while keeping user only enter numeric values and formatting the SSN with dashes.

Here is a fiddle link:

https://jsfiddle.net/7f8p83am/

$('#ssn').keyup(function() {
    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    var sizes = [3, 2, 4];
    var maxSize = 10;

    for (var i in sizes) {
      if (val.length > sizes[i]) {
        newVal += val.substr(0, sizes[i]) + '-';
        val = val.substr(sizes[i]);
      } else { 
        break; 
      }       
    }

    newVal += val;
    this.value = newVal;  
});   

Obviously, the replace is getting rid of *. Any ideas on how to do this?

thanks in advance.


Solution

  • You could consider removing all non-digits and asterisks as they were entered and replacing digits with asterisk :

    // Remove all non-digits/asterisks and replace digits with asterisks
    var val = this.value.replace(/[^\d\*]/g, '').replace(/\d/g,'*');
    

    Additionally, you may want to try adding a maxlength attribute on your element as well to prevent it from continuing :

    <input id='ssn' maxlength='11'/>
    

    Finally, you will likely want to consider storing a hidden field or variable that will store your proper SSN value so that you can post it to the server as expected.

    Example

    enter image description here

    <!DOCTYPE html>
    <html>
    
    <head>
      <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    
    <body>
      <input id='ssn' maxlength='11' />
      <script>
        $(function() {
          $('#ssn').keyup(function() {
            var val = this.value.replace(/[^\d\*]/g, '').replace(/\d/g, '*');
            var newVal = '';
            var sizes = [3, 2, 4];
            var maxSize = 10;
    
            for (var i in sizes) {
              if (val.length > sizes[i]) {
                newVal += val.substr(0, sizes[i]) + '-';
                val = val.substr(sizes[i]);
              } else {
                break;
              }
            }
    
            newVal += val;
            this.value = newVal;
          });
        });
      </script>
    </body>
    
    </html>