Permalink
Browse files

Merge pull request #120 from mreinstein/master

support for regular expressions in coercion
  • Loading branch information...
2 parents 46f6628 + 2f12c83 commit a3b353ab47a49e014cca2155a36a5cf92b4635cc @tj committed Jun 13, 2013
Showing with 29 additions and 2 deletions.
  1. +6 −0 Readme.md
  2. +23 −2 index.js
View
@@ -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:
View
@@ -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);

0 comments on commit a3b353a

Please sign in to comment.