Data masking is a very common requirement in the front end side in many projects. In this article, we will see how to perform masking using jQuery with suitable example.
Suppose we have a text box control where the person want's to type the Credit Card Number(CCN).
Let's take a scenario of Credit card number
A typical CCN looks like 4859 4752 4856 1586. As soon as the character passed on to the 8th character, the masking will start by displaying asterisk (*) which will go on till 15th character and again the numbers will be visible in the text box from 16th character on wards. So the final output will be 4859 47** **** 1586. And also we need to retain the original value.
The solution needs to be provided by using JQuery. In this article we will look into the problem by providing a solution with an explanation for the same.
Masking code in jQuery
Let us first look into the code
var originalValue = "";
originalValue += String.fromCharCode(e.which);
var CCNValue = $(this).val();
$(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/[0-9]/g , "*") + CCNValue.substring(15));
Credit Card number: <input type="text" id="txtCCN" maxlength=19 /><br/>
<input type="button" value="Original Value" id="btnOriginal" name="btnOriginal"/>
Masking Code Explanation
We have declared a variable by the name
originalValue. Then by using the
fromCharCode which converts a Unicode number into a character, we are capturing the values to that variable. Since the user has to type every character, henceforth, we have written the code in the
Keyup function of the textbox control. The
which property of the event object contains the key code of the key which was pressed to trigger the event. And the
fromCharCode function converts that to character. Then we are holding the value/key being pressed to a variable
CCNValue and by applying the regular expression we are replacing/masking the characters at the needed position.
CCNValue.substring(7, 15).replace(/[0-9]/g , "*")
On Original Value button click, we were displaying the original value of the Credit Card Number entered by the user in alert box.
Hope this article has clearly shown as how to mask the values using regular expression and we all have enjoyed the same. Thanks for reading. Zipped file attached.