1

I have seen the possibility to limit the way the text will show in a form. For instance, if it's a credit card, when the user writes, automatically a space is created between 4 numbers. How to do that?

(I am not talking about regex validation when the user click submit but before that, when the user writes the numbers in the input)

<form action='externs/select-insert.php' method='post'>
 <input type='text' id='card' name='card' value='### ###'>
</form>
Nrc
  • 9,577
  • 17
  • 67
  • 114
  • 1
    What you're looking for might be [input masking](https://stackoverflow.com/questions/12578507/how-to-implement-an-input-with-a-mask)? – castis Sep 11 '18 at 17:10

1 Answers1

3

You can perform that this way, using EventListener and a replace modification of the input value on keydown ( not change because it will be triggered only when input is not on focus anymore )

document.querySelector('#card').addEventListener('keydown', (e) => {
    e.target.value = e.target.value.replace(/(\d{4})(\d+)/g, '$1 $2')
})
/* Jquery */
$('#card').keyup(function() {
  $(this).val($(this).val().replace(/(\d{4})(\d+)/g, '$1 $2'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='externs/select-insert.php' method='post'>
 <input type='text' id='card' name='card' value='### ###'>
</form>
Bonlou
  • 472
  • 2
  • 9
  • This snippet will not work if you occult numbers using a non numeric symbol (which will probably be the case). Simply change the `d` in the replace by your matching character. – Bonlou Sep 11 '18 at 17:35
  • I try to adapt that to jQuery and I have problems, can you help? – Nrc Sep 11 '18 at 17:49