T E C h O C E A N H U B

Number masking Javascript formatter/validator function.Can be used for sin, credit card masking.

In this post, I have tried to create a simple Javascript function, which allows us to enter a number and mask the number on focus-out event in the textbox. This formatter is mostly used to enter a credit card, sin number.

<!DOCTYPE html>    
<script>             
 function maskFormatter(id) {                              
      var originalValue=document.getElementById(id).value;           
      document.getElementById(id).setAttribute("orginalValue",originalValue);           
      var firstsixchar=originalValue.substring(0,6)           
      firstsixchar=firstsixchar.replace(firstsixchar,"xxxxxxx")              
      var lastchar=originalValue.substring(6)           
      var replaceValue=firstsixchar+lastchar;            
      document.getElementById(id).value=replaceValue;                                  
   }                 
  function makevalueOriginal(id) {            
     var originalValue=document.getElementById(id).getAttribute('orginalValue');
     document.getElementById(id).value=originalValue;       
    }     
  function isNumberKey(evt){            
    var charCode = (evt.which) ? evt.which : evt.keyCode            
    if (charCode > 31 && (charCode < 48 || charCode > 57))              
       return false;            
       return true;       
    }              
</script>   
    <body>               
       Mask number:        
       <input id="sinnumber" maxlength="9" type="text" onkeypress="return isNumberKey(event)" onfocusout="maskFormatter('sinnumber')" onfocusin="makevalueOriginal('sinnumber')">    
    </body>
</html>

Output:987546121 to XXXXXX121

Feel free to try this code and comment below.

Copyright ©TechOceanhub All Rights Reserved.