Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support for regular expressions in coercion #120

Merged
merged 1 commit into from
Jun 13, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
25 changes: 23 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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]);
}

Expand Down Expand Up @@ -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);
Expand Down