droid
droid

Reputation: 621

How can i mask a string while typing in reactjs

This little baby here can mask a string

function format(value, pattern) {
    var i = 0,
        v = value.toString();
    return pattern.replace(/#/g, _ => v[i++]);
}

console.log(format(123456789, '## ## ## ###'));

But i want it to mask it while typing

Upvotes: 1

Views: 4686

Answers (1)

A. Ecrubit
A. Ecrubit

Reputation: 609

You can do that using onChange on your input and React's state to store the masked input.

How does it works :

  • I use : result.substr(0, result.indexOf('u')) when the input isn't long enough to get what comes before undefined.

  • I enable user to delete some characters by checking the length of target.value and not applying the mask if the user just deleted some characters.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state =  {
      code: null,
    }
  }
  
  format  =  (value, pattern) => {
    let i = 0,
        v = value.toString();
    let result =  pattern.replace(/#/g, _ => v[i++]);
    if (value.replace(/\s/g, '').length < 9) {
      return result.substr(0, result.indexOf('u')); 
    }
      return result; 
  }
  
  handleInput = ({target}) => {
    // enable user to delete characters
    if(this.state.code && (target.value.length < this.state.code.length)) {
      this.setState({code: target.value})
      return;
    }
    this.setState({
      code: this.format(target.value.replace(/\s/g, ''), '## ## ## ###')
    })
  }

  render() {
    return (
      <div>
        <h1>Masked Input :</h1>
        <input 
          onChange={this.handleInput} 
          value={this.state.code}
          />
      </div>
    );
  }
}


React.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions