Masking inputs any field and values

泄露秘密 提交于 2019-12-13 09:14:32

问题


I would like to know how to get the length of an input and replace everything between the values start and end but leave 2 chars and both ends.

I don't want to predefine the length as I want it to work on any input with any value and still be able to read the values with PHP when form submitted.

Input: Hello world street 12 Output: He*** ***** ****** 12

Input: 185445414631 Output: 18********31

Js lib: https://github.com/igorescobar/jQuery-Mask-Plugin

My code: https://jsfiddle.net/k4y0ctho/1/


回答1:


if your output is acceptable on other field, this might be useful

$("#input").on("keyup", function() {
 
  var input = $(this).val().split("")
  var res = $.map(input, (el, ix) => {
    return ix < 2 || ix > input.length - 3? el:"*"
  })

  $("#output").html(res.join(""));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="password" id="input" />
<br><span id="output"></span>



回答2:


If you are using jQuery what you can do is :

// Util function to mask the value
function maskValue(value) {
    if (typeof value !== 'string' || value.length <= 4) {
        return value;
    }
    return value.split('').map((v, i) => { return (i > 1 && i < value.length - 2 ? '*' : v); }).join('');
}

// actual value (not masked)
let actualValue = '';

// keyup event to handle new input and mask the value
$("#my-input").on("keyup", function(event) {
    if (event.key === 'Backspace') {
        actualValue = actualValue.substring(0, actualValue.length - 1);
    }
    else {
        actualValue += event.key;
    }
    $('#my-input').val(maskValue(actualValue));
});

Please keep in mind that this is not perfect as it only supports normal keys (letters, numbers, symbols) and the backspace button.



来源:https://stackoverflow.com/questions/46280652/masking-inputs-any-field-and-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!