From 2f12c83567f7e5c02e70b2039925d24933a83db2 Mon Sep 17 00:00:00 2001 From: Mike Reinstein Date: Mon, 21 Jan 2013 19:23:08 -0800 Subject: [PATCH] support for RegExp coercion --- Readme.md | 6 ++++++ index.js | 25 +++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index f93f3622a..107932a71 100644 --- a/Readme.md +++ b/Readme.md @@ -185,6 +185,12 @@ program.prompt('Birthdate: ', Date, function(date){ }); ``` +```js +program.prompt('Email: ', /^.+@.+\..+$/, function(email){ + console.log('email: %j', email); +}); +``` + ## .password(msg[, mask], fn) Prompt for password without echoing: diff --git a/index.js b/index.js index bddca73af..1f99634db 100644 --- a/index.js +++ b/index.js @@ -811,6 +811,25 @@ Command.prototype.promptForDate = function(str, fn){ }); }; + +/** + * Prompt for a `Regular Expression`. + * + * @param {String} str + * @param {Object} pattern regular expression object to test + * @param {Function} fn + * @api private + */ + +Command.prototype.promptForRegexp = function(str, pattern, fn){ + var self = this; + this.promptSingleLine(str, function parseRegexp(val){ + if(!pattern.test(val)) return self.promptSingleLine(str + '(regular expression mismatch) ', parseRegexp); + fn(val); + }); +}; + + /** * Single-line prompt. * @@ -820,7 +839,10 @@ Command.prototype.promptForDate = function(str, fn){ */ Command.prototype.promptSingleLine = function(str, fn){ - if ('function' == typeof arguments[2]) { + // determine if the 2nd argument is a regular expression + if (arguments[1].global !== undefined && arguments[1].multiline !== undefined) { + return this.promptForRegexp(str, arguments[1], arguments[2]); + } else if ('function' == typeof arguments[2]) { return this['promptFor' + (fn.name || fn)](str, arguments[2]); } @@ -879,7 +901,6 @@ Command.prototype.promptMultiLine = function(str, fn){ Command.prototype.prompt = function(str, fn){ var self = this; - if ('string' == typeof str) { if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); this.promptMultiLine(str, fn);