クレジットカード、電話番号、日付など文字列で入力すれども入力欄に区切りが欲しくなる場合があります。Cleave.js を使うとこの区切りを簡易に実装できます。
nosir/cleave.js: Format input text content when you are typing…
Cleave.js – Format input text content when you are typing
Cleave.js は npm で公開されているライブラリであり、次の様に使えます
# install npm install --save cleave.js
1 2 3 4 5 6 | import Cleave from 'cleave.js' ; // 第一引数に適用対象のセレクターを用意 new Cleave( 'input[name="cc-number"]' , { creditCard: true , // このオプション内でどの区切りを使うか定義 }); |
頭が 4 から始まれば VISA カード、51 から始まれば Mastercard の様に識別していい感じに区切ってくれます。また、半角数字のみの様な入力バリデーションもしてくれます。
React 上で使う時はおおむね次の様に input 要素のラッパーコンポーネントとして扱うとライフサイクルを考慮せずに済み、楽ができます。
nosir/cleave.js: Format input text content when you are typing…#reactjs-component-usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class MyComponent extends React.Component { constructor(props, context) { super(props, context); this.onCreditCardChange = this.onCreditCardChange.bind(this); this.onCreditCardFocus = this.onCreditCardFocus.bind(this); } onCreditCardChange(event) { // formatted pretty value console.log(event.target.value); // raw value console.log(event.target.rawValue); } onCreditCardFocus(event) { // update some state } render() { return ( < Cleave placeholder = "Enter your credit card number" options={{creditCard: true}} onFocus={this.onCreditCardFocus} onChange={this.onCreditCardChange} /> ); } } |