Reputation: 474
Inside a partialview, there is a textbox field binded to a model property. This text box is meant for sensitive information. So,I would like to mask the last few characters with asterisk(*).
If I use EditorFor() with input type set to "password", then all the characters are masked, which doesn't serve my purpose.
My desired functionality is 1) The last 4 characters in the text box should be displayed as ****(even while user enters the input, not just out of text box focus 2) The data sent to the controller must contain the actual value.
Please suggest.
Upvotes: 1
Views: 3047
Reputation: 2143
You can do it this way.
@model WebApplication1.Models.MyModel
@{
ViewBag.Title = "Home Page";
}
<br/>
<label>Enter your SSN</label>
<input type="text" id="visiblesecret"/>
@Html.HiddenFor(m=>m.MySensitiveField,new{@id="secret"})
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$('body').on('keyup', '#visiblesecret', function(event) {
var typedtext = $('#visiblesecret').val();
$('#secret').val(typedtext);
if (typedtext.length >= 7) {
var len = typedtext.length;
var nonSecretChars = '';
var secret = '';
switch (len) {
case 7:
nonSecretChars = typedtext.substring(0, len - 1);
secret = nonSecretChars + '*';
break;
case 8:
nonSecretChars = typedtext.substring(0, len - 2);
secret = nonSecretChars + '**';
break;
case 9:
nonSecretChars = typedtext.substring(0, len - 3);
secret = nonSecretChars + '***';
break;
case 10:
nonSecretChars = typedtext.substring(0, len - 4);
secret = nonSecretChars + '****';
break;
default:
alert("Invalid SSN");
$('#secret').val('');
$('#visiblesecret').val('');
return;
}
$('#visiblesecret').val(secret);
//alert('You entered ' + $('#secret').val());
}
});
});
</script>
Upvotes: 1
Reputation: 18863
If you want to hold the value of the last 4 just in case your requirements change do the following
//var last4 = myString.Substring(myString.Length - 4, 4);
If you want to store the first 5 characters do the following
//myString.Substring(myString.Length - 9, 5)
var maskDelim = new string('*', 4);
var myString = "123456789";
var maskResults = myString.Substring(0, 5);
maskResults = maskResults + maskDelim;
Upvotes: 1