• Stars
    star
    304
  • Rank 137,274 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Standalone input mask implementation, independent of any GUI

inputmask-core Build Status

A standalone input mask implementation, which is independent of any GUI.

InputMask encapsulates editing operations on a string which must conform to a fixed-width pattern defining editable positions and the types of characters they may contain, plus optional static characters which may not be edited.

Install

npm install inputmask-core

Usage

Importing and creating an instance:

var InputMask = require('inputmask-core')

var mask = new InputMask({pattern: '11/11/1111'})

Examples of editing a mask:

/*  Invalid input is rejected */
mask.input('a')
// → false

/* Valid input is accepted */
mask.input('1')
// → true
mask.getValue()
// → '1_/__/____'

/* Editing operations update the cursor position */
mask.selection
// → {start: 1, end: 1}

/* Pasting is supported */
mask.paste('2345678')
// → true
mask.getValue()
// → '12/34/5678'

/* Backspacing is supported */
mask.backspace()
// → true
mask.getValue()
// → '12/34/567_'

/* Editing operations also know how to deal with selected ranges */
mask.selection = {start: 0, end: 9}
mask.backspace()
// → true
mask.getValue()
// → '__/__/____'

/* Undo is supported */
mask.undo()
// → true
mask.getValue()
// → '12/34/567_'
mask.selection
// → {start: 0, end: 9}

/* Redo is supported */
mask.redo()
mask.getValue()
// → '__/__/____'
mask.selection
// → {start: 0, end: 0}

API

InputMask(options: Object)

Constructs a new InputMask - use of new is optional, so these examples are equivalent:

var mask = new InputMask({pattern: '1111-1111', value: '1234-5678'})
var mask = InputMask({pattern: '1111-1111', value: '1234-5678'})

InputMask options

pattern

A masking pattern must be provided and must contain at least one editable character, or an Error will be thrown.

The following format characters define editable parts of the mask:

  • 1 - number
  • a - letter
  • A - letter, forced to upper case when entered
  • * - alphanumeric
  • # - alphanumeric, forced to upper case when entered

If you need to include one of these characters as a static part of the mask, you can escape them with a preceding backslash:

var mask = new InputMask({pattern: '\\A11 \\1AA', value: 'A99 1ZZ'})
mask.getValue()
// → 'A99 1ZZ'

If you need to include a static backslash in a pattern, you must escape it:

var mask = new InputMask({pattern: '\\\\A11\\\\', value: 'Z98'})
mask.getValue()
// → '\\Z98\\'

Otherwise, all other characters are treated as static parts of the pattern.

Example patterns

  • Credit card number: 1111 1111 1111 1111
  • Date: 11/11/1111
  • ISO date: 1111-11-11
  • Time: 11:11
  • Canadian postal code: A1A 1A1
  • Norn Iron license plate: AAA 1111

formatCharacters

An object defining additional custom format characters to use in the mask's pattern.

When defining a new format character, a validate() function is required and a format() function can optionally be defined to modify the validated character before adding it to the mask's value.

For example this is how you would define w as a new format character which accepts word character input (alphanumeric or underscore) and forces it to lower case when entered:

var mask = new InputMask({
  pattern: 'Awwwww', // An uppercase letter followed by 5 word characters
  formatCharacters: {
    'w': {
      validate: function(char) { return /\w/.test(char) }
      transform: function(char) { return char.toLowerCase() }
    }
  }
})

To override a built-in format character, pass its character as a property of this object along with the new definition.

To disable a built-in format character, pass its character as a property of this object with a null value:

var mask = new InputMask({
  pattern: 'A1111', // Treats the 'A' as static
  formatCharacters: {
    'A': null
  }
})

placeholderChar : string

The character which is used to fill in editable slots for which there is no input yet when getting the mask's current value.

Defaults to '_'; must be a single character.

var mask = new InputMask({pattern: '11/11/1111', placeholderChar: ' '})
mask.input('1')
// → true
mask.getValue()
// → '1 /  /    '

value : string

An optional initial value for the mask.

selection : {start: number; end: number}

An optional default selection - defaults to {start: 0, end: 0}, placing the cursor before the first character.

isRevealingMask : boolean

An optional property that, if true, progressively shows the mask as input is entered. Defaults to false

Example: Given an input with a mask of 111-1111 x 111, a value of 47, and isRevealingMask set to true, then the input's value is formatted as 47 Given the same input but with a value of 476, then the input's value is formatted as 476- Given the same input but with a value of 47 3191, then the input's value is formatted as 47_-3191 x

InputMask editing methods

Editing methods will not allow the string being edited to contain invalid values according to the mask's pattern.

Any time an editing method results in either the value or the selection changing, it will return true.

Otherwise, if an invalid (e.g. trying to input a letter where the pattern specifies a number) or meaningless (e.g. backspacing when the cursor is at the start of the string) editing operation is attempted, it will return false.

input(character: string) : boolean

Applies a single character of input based on the current selection.

  • If a text selection has been made, editable characters within the selection will be blanked out, the cursor will be moved to the start of the selection and input will proceed as below.

  • If the cursor is positioned before an editable character and the input is valid, the input will be added. The cursor will then be advanced to the next editable character in the mask.

  • If the cursor is positioned before a static part of the mask, the cursor will be advanced to the next editable character.

After input has been added, the cursor will be advanced to the next editable character position.

backspace() : boolean

Performs a backspace operation based on the current selection.

  • If a text selection has been made, editable characters within the selection will be blanked out and the cursor will be placed at the start of the selection.

  • If the cursor is positioned after an editable character, that character will be blanked out and the cursor will be placed before it.

  • If the cursor is positioned after a static part of the mask, the cursor will be placed before it.

paste(input: string): boolean

Applies a string of input based on the current selection.

This behaves the same as - and is effectively like - calling input() for each character in the given string with one key difference - if any character within the input is determined to be invalid, the entire paste operation fails and the mask's value and selection are unaffected.

Pasted input may optionally contain static parts of the mask's pattern.

InputMask history methods

An InputMask creates a new history snapshot each time you:

  • Perform a different type of editing operation to the previous editing operation.
  • Perform an editing operation with the cursor in a different position from where it was left after a previous editing operation.
  • Perform an editing operation with a text selection.

History methods allow you to step backwards and forwards through these snapshots, updating value and selection accordingly.

If you perform an editing operation while stepping backwards through history snapshots, all snapshots after the current one will be disposed of.

A history method returns true if a valid history operation was performed and value and selection have been updated.

Otherwise, if an invalid history operation is attempted (e.g. trying to redo when you've already reached the point undoing started from) it will return false.

undo() : boolean

Steps backwards through history snapshots.

redo() : boolean

Steps forwards through history snapshots.

InputMask public properties, getters & setters

emptyValue : string

The value the mask will have when none of its editable data has been filled in.

selection : {start: number; end: number}

The current selection within the input represented as an object with start and end properties, where end >= start.

If start and end are the same, this indicates the current cursor position in the string, otherwise it indicates a range of selected characters within the string.

selection will be updated as necessary by editing methods, e.g. if you input() a valid character, selection will be updated to place the cursor after the newly-inserted character.

If you're using InputMask as the backend for an input mask in a GUI, make sure selection is accurate before calling any editing methods!

setSelection(selection: {start: number; end: number}) : boolean

Sets the selection and performs an editable cursor range check if the selection change sets the cursor position (i.e. start and end are the same).

If the mask's pattern begins or ends with static characters, this method will prevent the cursor being placed prior to a leading static character or beyond a tailing static character. Only use this method to set selection if this is the behaviour you want.

Returns true if the selection needed to be adjusted as described above, false otherwise.

getValue() : string

Gets the current value in the mask, which will always conform to the mask's pattern.

getRawValue() : string

Gets the current value in the mask without non-editable pattern characters.

This can be useful when changing the mask's pattern, to "replay" the user's input so far into the new pattern:

var mask = new InputMask({pattern: '1111 1111', value: '98781'})
mask.getValue()
// → '9878 1___'
mask.getRawValue()
// → '98781'

mask.setPattern('111 111', {value: mask.getRawValue()})
mask.getValue()
// → '987 81_'

setValue(value: string)

Overwrites the current value in the mask.

The given value will be applied to the mask's pattern, with invalid - or missing - editable characters replaced with placeholders.

The value may optionally contain static parts of the mask's pattern.

setPattern(pattern: string, options: ?Object)

Sets the mask's pattern. The mask's value and selection will also be reset by default.

setPattern options

value : string

A value to be applied to the new pattern - defaults to ''.

selection : {start: number; end: number}

Selection after the new pattern is applied - defaults to {start: 0, end: 0}.

MIT Licensed

More Repositories

1

nwb

A toolkit for React, Preact, Inferno & vanilla JS apps, React libraries and other npm modules for the web, with no configuration (until you need it)
JavaScript
5,572
star
2

react-hn

React-powered Hacker News client
JavaScript
2,179
star
3

control-panel-for-twitter

Browser extension which gives you more control over your Twitter timeline and adds missing features and UI improvements - available for desktop and mobile browsers
JavaScript
1,924
star
4

react-maskedinput

Masked <input/> React component
JavaScript
730
star
5

newforms

Isomorphic form-handling for React
JavaScript
642
star
6

msx

JSX for Mithril.js 0.x
JavaScript
362
star
7

react-heatpack

A 'heatpack' command for quick React development with webpack hot reloading
JavaScript
347
star
8

babel-plugin-react-html-attrs

Babel plugin which transforms HTML and SVG attributes on JSX host elements into React-compatible attributes
JavaScript
177
star
9

isomorphic-lab

Isomorphic React experimentation
JavaScript
144
star
10

DOMBuilder

DOM builder with multiple output formats
JavaScript
119
star
11

react-auto-form

Simplifies getting user input from forms via onChange and onSubmit events, using DOM forms APIs
JavaScript
116
star
12

react-router-active-component

Factory function for React components which are active for a particular React Router route
JavaScript
113
star
13

get-form-data

Gets form and field data via form.elements
JavaScript
106
star
14

react-lessons

Tool for creating and taking interactive React tutorials
JavaScript
103
star
15

react-examples

React… examples…
JavaScript
98
star
16

ad-hoc-reckons

JavaScript
85
star
17

control-panel-for-youtube

Browser extension which gives you more control over YouTube by adding missing options and UI improvements - for desktop & mobile browsers
JavaScript
81
star
18

remote_control_for_vlc

A VLC remote control written with Flutter
Dart
77
star
19

react-octicon

A GitHub Octicons icon React component
JavaScript
75
star
20

gatsby-plugin-dark-mode

A Gatsby plugin which handles some of the details of implementing a dark mode theme
JavaScript
68
star
21

react-filtered-multiselect

Filtered multi-select React component
JavaScript
61
star
22

redux-todomvc-es5

ES5 version of the Redux todomvc example
JavaScript
59
star
23

react-router-form

<Form> is to <form> as <Link> is to <a>
JavaScript
56
star
24

redux-action-utils

[DEPRECATED] Factory functions for reducing action creator boilerplate (pun not intended)
JavaScript
48
star
25

newforms-bootstrap

Components for rendering a newforms Form using Bootstrap 3
JavaScript
48
star
26

package-config-checker

Checks if your dependencies have package.json files config or an .npmignore for packaging
JavaScript
47
star
27

obs-bounce

OBS script to bounce a scene item around, DVD logo style or throw & bounce with physics
Lua
44
star
28

lifequote

React port of a life insurance quick quoting application
JavaScript
39
star
29

newforms-examples

Examples repository for newforms / React
JavaScript
32
star
30

ideas-md

A float-to-the-top ideas log built with React
JavaScript
32
star
31

djangoffice

Project management/CRM for small offices - Clients, Jobs, Tasks, Rates, Activities, Timesheets, Contacts, Invoices etc. etc.
Python
30
star
32

tabata_timer

A Tabata training interval timer written with Flutter.
Dart
30
star
33

react-gridforms

React components for Gridforms form layout
JavaScript
29
star
34

newforms-gridforms

Grid Forms integration for newforms
CSS
27
star
35

comments-owl-for-hacker-news

Browser extension which makes it easer to follow comment threads on Hacker News across multiple visits, allows you to annotate and mute users, and other UI tweaks and mobile UX improvements
JavaScript
27
star
36

astro-lazy-youtube-embed

Embed YouTube videos with a static placeholder which only embeds when you click
Astro
26
star
37

reactodo

Multiple localStorage TODO lists, built with React
JavaScript
25
star
38

forum

A basic Django forum app with metaposts; uses redis for stats/tracking
Python
25
star
39

react-plain-editable

[DEPRECATED] React component for editing plain text via contentEditable
JavaScript
21
star
40

ui-lib-samples

Misc impls of functionality with various JavaScript UI libs
HTML
15
star
41

react-dsl

Generate React components as DSLs for structural markup, such as that of CSS frameworks
CSS
14
star
42

soclone

The beginnings of a Stack Overflow clone
Python
14
star
43

concur

Sugar for infectious JavaScript inheritance, metaprogramming & mixins
JavaScript
14
star
44

gulp-msx

Precompile Mithril views which use JSX into JavaScript
JavaScript
14
star
45

manage-twitter-engagement

Manage "engagement" on Twitter by moving retweets and algorithmic tweets to their own lists
JavaScript
14
star
46

hta-localstorage

Basic localStorage implementation for Internet Explorer HTML Applications (HTA)
JavaScript
12
star
47

caveat-utilitor

Personal GtHub repo status badges
12
star
48

sublime-sort-javascript-imports

Sublime Text package for sorting selected JavaScript import/require() lines by module name
Python
11
star
49

greasemonkey

User scripts
JavaScript
11
star
50

nwb-from-create-react-app

Examples of using nwb as an alternative to ejecting from create-react-app
JavaScript
11
star
51

nwb-sass

Sass plugin for nwb
JavaScript
11
star
52

templates

Reusable templates for various kinds of projects
HTML
10
star
53

sacrum

One codebase, two environments - single-page JavaScript apps in the browser, forms 'n links webapps on Node.js for almost-free
JavaScript
10
star
54

isomorph

Shared utilities for browsers and Node.js
JavaScript
9
star
55

update-object

Mirror of Facebook's update() immutability helper
JavaScript
9
star
56

substitute

Edits Twitter typos using s/this/that/ expressions
JavaScript
7
star
57

react-playground

React component for creating interactive coding playgrounds with preset examples
JavaScript
7
star
58

dinnertime

Cooking timer & scheduler with spoken instructions
JavaScript
7
star
59

validators

Validators which can be shared between browsers and Node.js
JavaScript
7
star
60

nwb-react-tutorial

An implementation of the React Tutorial using nwb's middleware
JavaScript
6
star
61

sublime-react-snippets

Sublime Text snippets for writing React components
JavaScript
6
star
62

eslint-config-jonnybuchanan

Personal ESLint setup as a single devDependency
JavaScript
6
star
63

insin.github.io

Static project & demo hosting
JavaScript
6
star
64

react-objecteditor

An <ObjectEditor/> React component
JavaScript
5
star
65

nwb-thinking-in-react

An implementation of the Thinking in React tutorial using nwb
JavaScript
5
star
66

nwb-examples

Examples of configuring nwb
JavaScript
5
star
67

stargaze

Watch a GitHub repo's star count, with change notifications on your desktop
JavaScript
5
star
68

nwb-less

Less plugin for nwb
JavaScript
4
star
69

babel-preset-proposals

A Babel 7 preset to manage experimental proposal plugin dependencies and usage
JavaScript
4
star
70

urlresolve

Resolves paths against URL patterns
JavaScript
4
star
71

shilefare

Dead simple local, temporary file sharing with Node.js
JavaScript
4
star
72

couch25k

Java MIDlet which tracks intervals for the Couch-to-5k running program
Java
4
star
73

chainable-check

Create React.PropTypes-alike validators with an isRequired property
JavaScript
4
star
74

yak-stacker

An app for tracking your Yak Stack during programming sessions
4
star
75

cdogs-wii

Wii port of C-Dogs SDL using SDL Wii
C
4
star
76

deduped-babel-presets

[DEPRECATED] Babel 6 presets with shared dependencies manually deduplicated for npm2 compatibility
JavaScript
3
star
77

react-suggest

React components for implementing suggested completions
JavaScript
3
star
78

rllmuk-really-ignore-users

Really ignore ignored users, and ignore users in specific topics
JavaScript
3
star
79

react-split-date-input

Reusable split date input React component
JavaScript
3
star
80

njive

Node.js wrapper for the Jive API
JavaScript
3
star
81

bootstrap-4-nwb

Example app from "Using Bootstrap 4 from source with React and nwb"
CSS
3
star
82

react-node-time-tracker

A React clone of a Vue tutorial app
JavaScript
3
star
83

redbox-noreact

A fork of redbox-react which doesn't import React
JavaScript
3
star
84

POWDER-wii

Port files for the Wii version of POWDER ( http://www.zincland.com/powder/ )
C++
3
star
85

just-dadjokes

Just the jokes from /r/dadjokes
JavaScript
3
star
86

gulp-flatten-requires

Flattens relative require('./<path>/<module>') calls to require('./<module>')
JavaScript
3
star
87

pixel-shifter

A React component for pixel-shifting text elements
JavaScript
3
star
88

event-listener

Simple function for addEventListener() vs. addEvent()
JavaScript
3
star
89

lmms

Linux MultiMedia Studio working directory
Python
3
star
90

buildumb

Ultra-dumb exporter of Node.js modules for use in the browser
JavaScript
2
star
91

models

Models, models, everywhere. In the client and in the server.
JavaScript
2
star
92

countdown-file

Writes a countdown to a text file every second
JavaScript
2
star
93

django-vgdb

[OLD] Videogame database, opinion & story collector - begat django-mptt
Python
2
star
94

iswydt

Tumblejobs
JavaScript
2
star
95

twitter-searchite

Quick creation of sites driven by polling a Twitter search
JavaScript
2
star
96

stackoverflow

Code from investigating/answering StackOverflow questions
CSS
2
star
97

cookdandbombd-really-ignore-users

Really ignore ignored users
JavaScript
2
star
98

mixinstance

Mix new things into an instance's prototype chain
JavaScript
2
star
99

successcrm

JavaScript
2
star
100

rllmuk-ignore-topics

Hide topics and forums you're not interested in on the Rllmuk forum
JavaScript
2
star