Yargs: required positionals should support custom error messages

Created on 3 Apr 2020  路  3Comments  路  Source: yargs/yargs

It looks like there is no easy way to override error message for required positional argument:
https://github.com/yargs/yargs/blob/16ee006eb1597427c8a964b0f69d7b3ce8407ca2/lib/validation.js#L61

It would be nice if there was a mecanism similar to demandOption where a custom error string could be provided.

feature request

Most helpful comment

@bcoe I was thinking about:

  • allowing demandOption property for positional options (with a check that it can be truthy only if the positional is required)
  • making .addHandler('cmd <req> [opt]'... calling .positional('req', { demandOption: true }) and .positional('opt', {})
  • removing positionalCount() as required positional presence would already be checked with other required options
  • cleaning up cmdToParseOptions() as most of its code would no longer be necessary
  • etc.

As a side effect .demandOption('req', message) would work too for positionals, and should answer @proppy 's needs.

All 3 comments

@proppy No, I'm afraid there is no way to do it at the moment.

@bcoe I think we should merge the required positional and required options validation. Not only would we simplify the validation code (which is my main interest here, to be honest :-)), but we would also allow the use of .demandOption for positionals, as is required here.

I will try to have a look at this once lib/command and yargs are tsified (doing both at the same time would be dangerous).

Note that it would be a breaking change, as it would have (positive) impacts on error and help messages for commands using positionals.

This seems like a reasonable feature request.

@proppy, I think I'm not 100% sure what you're referring to with _"we should merge the required positional and required options validation."_, this might be a proposal I haven't read yet? I agree that we should land the TypeScript conversion first.

@bcoe I was thinking about:

  • allowing demandOption property for positional options (with a check that it can be truthy only if the positional is required)
  • making .addHandler('cmd <req> [opt]'... calling .positional('req', { demandOption: true }) and .positional('opt', {})
  • removing positionalCount() as required positional presence would already be checked with other required options
  • cleaning up cmdToParseOptions() as most of its code would no longer be necessary
  • etc.

As a side effect .demandOption('req', message) would work too for positionals, and should answer @proppy 's needs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

steveharman picture steveharman  路  4Comments

bcoe picture bcoe  路  4Comments

atian25 picture atian25  路  4Comments

strugee picture strugee  路  5Comments

alexreg picture alexreg  路  4Comments