input-format
Formatting user's text input on-the-fly
See Demo
Installation
npm install input-format --save
Usage
Phone number formatting example
import { templateParser, templateFormatter, parseDigit } from 'input-format'
const TEMPLATE = '(xxx) xxx-xxxx'
const parse = templateParser(TEMPLATE, parseDigit)
const format = templateFormatter(TEMPLATE)
React Component usage
import { ReactInput } from 'input-format'
<ReactInput
value={this.state.phone}
onChange={phone => this.setState({ phone })}
parse={parse}
format={format}/>
Lower level API (for component developers)
import { InputController } from 'input-format'
const input = document.querySelector('input')
const inputController = new InputController(input, parse, format, onChange)
inputController.onCut(event)
inputController.onPaste(event)
inputController.onChange(event)
inputController.onKeyDown(event)
Lowest level API
import { parse, format } from 'input-format'
function parse_digit(character, value)
{
if (value.length < 10)
{
if (character >= '0' && character <= '9')
{
return character
}
}
}
function format_phone(value)
{
...
return {
text: '(800) 555-3535',
template: '(xxx) xxx-xxxx'
}
}
let value
let text = '(800) 555-3535'
let caret = 4
{ value, caret } = parse(text, caret, parse_digit)
value === '8005553535'
caret === 2
{ text, caret } = format(value, caret, format_phone)
value === '(800) 555-3535'
caret === 4
Contributing
After cloning this repo, ensure dependencies are installed by running:
npm install
This module is written in ES6 and uses Babel for ES5
transpilation. Widely consumable JavaScript can be produced by running:
npm run build
Once npm run build
has run, you may import
or require()
directly from
node.
After developing, the full test suite can be evaluated by running:
npm test
When you're ready to test your new functionality on a real project, you can run
npm pack
It will build
, test
and then create a .tgz
archive which you can then install in your project folder
npm install [module name with version].tar.gz
License
MIT