4

I'm trying to add a space after every 4 numbers in an input field.

here's my code :

    credit: function(e) {
        const val = e.target.value;
        const valArray = val.split(' ').join('').split('');
        if(isNaN(valArray.join('')))
            return;
        if(valArray.length === 17)
            return
        if(valArray.length % 4 === 0) {
            this.setState({ number: e.target.value + "  " });
        }else{
            this.setState({ number: e.target.value})
        }
  },

and here's the rules : user can write only numbers and length should 16 and add space after each 4 numbers.

the problem is :

1: at the end of the numbers there is a extra space that added after the last number

2: i can't use backspace to delete element (after pushing back space it will add space in front of the numbers)

Fiddle

Josh Pittman
  • 7,024
  • 7
  • 38
  • 66
Enzo
  • 198
  • 2
  • 11

3 Answers3

4

Here is a minimalistic example: https://jsfiddle.net/unah2qzf/

Key here is to set the onchange method

onChange(e) {
  var val = e.target.value;
  this.setState({
    number: val.replace(/\W/gi, '').replace(/(.{4})/g, '$1 ')
  });
}

im sure you can figure out from here how to restrict to numbers

Rohan Bhangui
  • 353
  • 2
  • 10
2

you need to check each item with the previous item to see if there is a space or not.

var val = e.target.value;
    const valArray = val.split(' ').join('').split('');
    var valSpace = val.split("")

    // to work with backspace
    if(valSpace[valSpace.length-1] == ' '){
        var valSpaceN = valSpace.slice(0, -2)
        val = valSpaceN.join("")
        this.setState({ number:val });
        return;
    }

    if(isNaN(valArray.join('')))
        return;
    if(valArray.length === 17)
        return
    if(valArray.length % 4 === 0 && valArray.length <= 15) {
        this.setState({ number: e.target.value + "  " });
    }else{

        this.setState({ number: e.target.value})
    }

Working Fiddle

Sadeghbayan
  • 1,163
  • 2
  • 18
  • 38
-1

Thank me later :P

prev:0,
    getInitialState: function() {
    return {number: ''};
  },
    credit: function(e) {
         const val = e.target.value;
        const valArray = val.split(' ').join('').split('');
        console.log(valArray)
        if(isNaN(valArray.join('')))
            return;
        if(valArray.length === 17)
            return
        if(valArray.length % 4 === 0 && this.prev < valArray.length) {
            this.setState({ number: e.target.value + "  " });
        }else{
        console.log()
            this.setState({ number: e.target.value})
        }
        this.prev = valArray.length
  },
sathish1409
  • 245
  • 3
  • 6
  • I've tested this in your fiddle, it worked. Just copy paste the above code to yours... Now you can press backspace – sathish1409 Dec 11 '19 at 05:46