简体   繁体   中英

Validate user input with whitespace

How to in real-time format user input? For example, the user puts A9364470240ZGS001 to the input field, and using JavaScript format it in the input field in real-time to be like: A 936 447 02 40 ZGS 001 ?

<div class="childDumpFile">
     <label for="ds">Dataset</label>
     <input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}">
</div>

If we suppose users have to write the characters one by one. This will work.

<body>
    <input type="text" class="form-control" id="ds" name="ds" onkeypress="keyPress()" maxlength="23">
</body>
<script>
    function keyPress() {
        var field = document.getElementById("ds");
        var text = field.value;
        if(text.length == 1 || text.length == 5 
        || text.length == 9 || text.length == 12
        || text.length == 15 || text.length == 19 ) {
            var newText = text + " ";
            field.value = newText;
        }
    }
</script>

I found the true answer. These expectations are naming as "input-mask" and if you'd like to use. You have to use 3. party libraries. Some of them listing in following sites:

Libraries 1 Libraries 2

I chose Cleave.js for your question. This is the demo:

<script src="https://nosir.github.io/cleave.js/dist/cleave.min.js"></script>
<script src="https://nosir.github.io/cleave.js/dist/cleave-phone.i18n.js"></script>
<script>
    function loadFunction() {
        // custom
        var cleaveCustom = new Cleave('.input-custom', {
            blocks: [1, 3, 3, 2, 2, 3, 3],
            delimiter: ' ',
        });
    }
</script>

<body onload="loadFunction()">
    A 936 447 02 40 ZGS 001
    <div class="container">
        <input class="input-custom" placeholder="Custom delimiter & blocks" />
    </div>
</body>

Here is a little example.

<div class="childDumpFile">
     <label for="ds">Dataset</label>
     <input type="text" class="form-control" id="ds" name="ds">
</div>

<div class="test_ds"></div>

JS with jquery.

$("#ds").change(function(){
    var ds_value = $("#ds").val();

var temp = ds_value;
temp = temp.substring(0,1) + " " + temp.substring(1, 4) + " " + temp.substring(4, 7) + " " + temp.substring(7, 9) + " " + temp.substring(9, 11) + " " + temp.substring(11, 14) + " " + temp.substring(14, 17);

  $("#ds").val(temp);
  $(".test_ds").html(temp);
});

Here is a demo - https://jsfiddle.net/Kistlak/7bkdtev8

First, you need add onchange="getTimeNow()" oninput="getTimeNow()" in to input

<input type="text" class="form-control" id="ds" name="ds" value="{{Request::get('ds') ?? ''}}" onchange="getTimeNow()" oninput="getTimeNow()">

Finally, you get event input text

<script>function getTimeNow(){console.log(new Date())}</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM