Enzo
Enzo

Reputation: 318

Adding a space after every 4 numbers in an input field in react

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

Upvotes: 4

Views: 6198

Answers (3)

Sadeghbayan
Sadeghbayan

Reputation: 1163

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

Upvotes: 2

sathish1409
sathish1409

Reputation: 275

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
  },

Upvotes: -1

Rohan Bhangui
Rohan Bhangui

Reputation: 373

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

Upvotes: 5

Related Questions