Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

support for regular expressions in coercion #120

Merged
merged 1 commit into from

2 participants

@mreinstein

@visionmedia commander.js is awesome! I hope this patch is useful to you.

@mreinstein

any feedback on this patch?

@tj tj merged commit a3b353a into tj:master

1 check passed

Details default The Travis build passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jan 22, 2013
  1. @mreinstein
This page is out of date. Refresh to see the latest.
Showing with 29 additions and 2 deletions.
  1. +6 −0 Readme.md
  2. +23 −2 index.js
View
6 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:
View
25 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);
Something went wrong with that request. Please try again.