Skip to content
NurulC edited this page Feb 20, 2017 · 13 revisions

Masked Input

Input Validation as you type, using only regular expression to perform the validation. To support this capability I had to implement a new kind of regular expression matcher. JavaScript has really good regular expression matching capability, but it as one serious limitation, you need the entire string.

var rx = /Red|Blue/;
rx.test('Blu');  // returns a false 

on the other hand

rx.test('Blue'); // returns a true

So you cannot use a regular expression to check for a partial match. So suppose we want to validate a US phone number:

var rx = /[0-9]{3}-[0-9]{3}-[0-9]{4}/; // note [0-9] could be replaces '\d', but it is less clear
rx.test('917-'); 

The bottom line is that, regexp will not give any indication if a string partially patches the regular expression. Because of this, regular expression i no useful for validating input as you type. So we need an entirely new kind of regular expression matcher. Fortunately Ken Thompson (the co-creator of Unix) and the inventor of regular expression as a pattern matching tool, had an algorithm that does exactly what we need - an incremental regular expression matcher (I was not aware of the algorithm when I was building my algorithm and ended up rediscovering it). The algorithm that is used is written in Javascript and cab be found here (NPM package). Although the algorithm is largely the same, but it targeted at incremental string matching.

The basic idea

Code Example

import {incrRegEx, DONE} from 'incr-regex-package';

// example match a US phone number
var rx = incrRegEx( /\\d{3}-\\d{3}-\\d{4}/ );

// we are trying to match '212-409-5123'

rx.match('2'); // => true,  matched "2..."
rx.match('-'); // => false , i.e. it did not accept the character

rx.match('1'); // => true ,  matched '21...'
rx.match('2'); // =>  true   matched '212..'
rx.match('4'); // =>  false , expected '-'

rx.match('-'); // => true , matched '212-...'
....

rx.match('3'); // => true,  matched '212-409-5123'

rx.state() === DONE; // true
Clone this wiki locally