Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 276
Enzo Avatar asked Oct 23 '25 15:10

Enzo


2 Answers

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

like image 135
Rohan Bhangui Avatar answered Oct 26 '25 04:10

Rohan Bhangui


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

like image 39
Sadeghbayan Avatar answered Oct 26 '25 05:10

Sadeghbayan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!