or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

command-system.mdcore-parser.mdhelp-output.mdindex.mdoption-definition.mdparsing.mdvalidation.md

validation.mddocs/

0

# Validation and Requirements

1

2

Validate arguments, define required options and commands, and set up option relationships.

3

4

## Capabilities

5

6

### Required Commands

7

8

Specify minimum and maximum number of commands.

9

10

```javascript { .api }

11

/**

12

* Require minimum/maximum number of commands

13

* @param min - Minimum number of commands (default: 1)

14

* @param max - Maximum number of commands

15

* @param minMsg - Message for too few commands

16

* @param maxMsg - Message for too many commands

17

* @returns YargsInstance for chaining

18

*/

19

demandCommand(min?: number, max?: number | string, minMsg?: string | null, maxMsg?: string | null): YargsInstance;

20

```

21

22

**Usage Examples:**

23

24

```javascript

25

// Require at least one command

26

yargs()

27

.command('start', 'start service')

28

.command('stop', 'stop service')

29

.demandCommand(1, 'You need at least one command before moving on')

30

.parse();

31

32

// Require exactly one command

33

yargs()

34

.command('build', 'build project')

35

.command('test', 'run tests')

36

.demandCommand(1, 1, 'Specify exactly one command', 'Too many commands specified')

37

.parse();

38

39

// Custom error messages

40

yargs()

41

.command('deploy', 'deploy app')

42

.demandCommand(1, 'Please specify a command to run')

43

.parse();

44

```

45

46

### Required Options

47

48

Make specific options mandatory.

49

50

```javascript { .api }

51

/**

52

* Make options required

53

* @param keys - Option name(s) or requirements object

54

* @param msg - Error message for missing option

55

* @returns YargsInstance for chaining

56

*/

57

demandOption(keys: string | string[] | Dictionary<string | undefined>, msg?: string): YargsInstance;

58

59

/**

60

* Require options or commands (legacy)

61

* @param keys - Option/command requirements

62

* @param max - Maximum value or error message

63

* @param msg - Error message

64

* @returns YargsInstance for chaining

65

*/

66

demand(keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true): YargsInstance;

67

68

/**

69

* Alias for demand()

70

*/

71

required(keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true): YargsInstance;

72

73

/**

74

* Alias for demand()

75

*/

76

require(keys: string | string[] | Dictionary<string | undefined> | number, max?: number | string[] | string | true, msg?: string | true): YargsInstance;

77

```

78

79

**Usage Examples:**

80

81

```javascript

82

// Single required option

83

yargs()

84

.option('config', { describe: 'Configuration file' })

85

.demandOption('config', 'Please provide a config file')

86

.parse();

87

88

// Multiple required options

89

yargs()

90

.options({

91

username: { describe: 'Username' },

92

password: { describe: 'Password' }

93

})

94

.demandOption(['username', 'password'])

95

.parse();

96

97

// Required options with custom messages

98

yargs()

99

.demandOption({

100

username: 'Username is required for authentication',

101

password: 'Password is required for authentication'

102

})

103

.parse();

104

```

105

106

### Option Conflicts

107

108

Define mutually exclusive options.

109

110

```javascript { .api }

111

/**

112

* Define conflicting options

113

* @param key1 - First option or conflicts map

114

* @param key2 - Second option name(s)

115

* @returns YargsInstance for chaining

116

*/

117

conflicts(key1: string | Dictionary<string | string[]>, key2?: string | string[]): YargsInstance;

118

```

119

120

**Usage Examples:**

121

122

```javascript

123

// Two conflicting options

124

yargs()

125

.option('json', { describe: 'Output as JSON' })

126

.option('xml', { describe: 'Output as XML' })

127

.conflicts('json', 'xml')

128

.parse();

129

130

// Multiple conflicts

131

yargs()

132

.conflicts({

133

json: ['xml', 'yaml'],

134

verbose: 'quiet',

135

stdin: 'file'

136

})

137

.parse();

138

```

139

140

### Option Implications

141

142

Define options that require other options.

143

144

```javascript { .api }

145

/**

146

* Define option implications (if X then Y is required)

147

* @param key - Option name or implications map

148

* @param value - Implied option name(s)

149

* @returns YargsInstance for chaining

150

*/

151

implies(key: string | Dictionary<string | number | (string | number)[]>, value?: string | number | (string | number)[]): YargsInstance;

152

```

153

154

**Usage Examples:**

155

156

```javascript

157

// Single implication

158

yargs()

159

.option('ssl', { describe: 'Enable SSL' })

160

.option('cert', { describe: 'SSL certificate path' })

161

.implies('ssl', 'cert')

162

.parse();

163

164

// Multiple implications

165

yargs()

166

.implies({

167

ssl: ['cert', 'key'],

168

auth: 'username',

169

database: ['host', 'port']

170

})

171

.parse();

172

173

// Positional implications

174

yargs()

175

.command('deploy <env>', 'deploy to environment')

176

.implies('env', 'config') // If env positional is provided, config is required

177

.parse();

178

```

179

180

### Custom Validation

181

182

Add custom validation functions.

183

184

```javascript { .api }

185

/**

186

* Add custom validation function

187

* @param f - Validation function that receives argv and options

188

* @param global - Whether validation applies globally or just to current context

189

* @returns YargsInstance for chaining

190

*/

191

check(f: (argv: Arguments, options: Options) => any, global?: boolean): YargsInstance;

192

```

193

194

**Usage Examples:**

195

196

```javascript

197

// Port range validation

198

yargs()

199

.option('port', { type: 'number' })

200

.check((argv) => {

201

if (argv.port && (argv.port < 1 || argv.port > 65535)) {

202

throw new Error('Port must be between 1 and 65535');

203

}

204

return true;

205

})

206

.parse();

207

208

// File existence validation

209

yargs()

210

.option('input', { describe: 'Input file' })

211

.check((argv) => {

212

if (argv.input && !require('fs').existsSync(argv.input)) {

213

throw new Error(`Input file does not exist: ${argv.input}`);

214

}

215

return true;

216

})

217

.parse();

218

219

// Async validation

220

yargs()

221

.option('url', { describe: 'URL to validate' })

222

.check(async (argv) => {

223

if (argv.url) {

224

try {

225

await fetch(argv.url);

226

return true;

227

} catch (error) {

228

throw new Error(`URL is not accessible: ${argv.url}`);

229

}

230

}

231

return true;

232

})

233

.parse();

234

235

// Global validation (applies to all commands)

236

yargs()

237

.check((argv) => {

238

if (argv.debug && argv.quiet) {

239

throw new Error('Cannot use --debug and --quiet together');

240

}

241

return true;

242

}, true)

243

.parse();

244

```

245

246

### Strict Mode

247

248

Enable strict parsing to catch unknown options and commands.

249

250

```javascript { .api }

251

/**

252

* Enable strict mode for unknown options/commands

253

* @param enabled - Whether to enable strict mode

254

* @returns YargsInstance for chaining

255

*/

256

strict(enabled?: boolean): YargsInstance;

257

258

/**

259

* Enable strict mode for unknown commands only

260

* @param enabled - Whether to enable strict command mode

261

* @returns YargsInstance for chaining

262

*/

263

strictCommands(enabled?: boolean): YargsInstance;

264

265

/**

266

* Enable strict mode for unknown options only

267

* @param enabled - Whether to enable strict option mode

268

* @returns YargsInstance for chaining

269

*/

270

strictOptions(enabled?: boolean): YargsInstance;

271

```

272

273

**Usage Examples:**

274

275

```javascript

276

// Full strict mode

277

yargs()

278

.option('verbose', { type: 'boolean' })

279

.command('build', 'build project')

280

.strict()

281

.parse();

282

// Will error on: --unknown-option or unknown-command

283

284

// Strict commands only

285

yargs()

286

.command('start', 'start service')

287

.command('stop', 'stop service')

288

.strictCommands()

289

.parse();

290

// Will error on unknown commands but allow unknown options

291

292

// Strict options only

293

yargs()

294

.option('port', { type: 'number' })

295

.strictOptions()

296

.parse();

297

// Will error on unknown options but allow unknown commands

298

```

299

300

### Deprecation

301

302

Mark options as deprecated with warnings.

303

304

```javascript { .api }

305

/**

306

* Mark option as deprecated

307

* @param option - Option name to deprecate

308

* @param message - Deprecation message or true for default message

309

* @returns YargsInstance for chaining

310

*/

311

deprecateOption(option: string, message: string | boolean): YargsInstance;

312

```

313

314

**Usage Examples:**

315

316

```javascript

317

// Basic deprecation

318

yargs()

319

.option('old-option', { describe: 'Legacy option' })

320

.deprecateOption('old-option', 'Use --new-option instead')

321

.parse();

322

323

// Default deprecation message

324

yargs()

325

.option('legacy', { describe: 'Legacy flag' })

326

.deprecateOption('legacy', true)

327

.parse();

328

```

329

330

### Getters for Validation State

331

332

Retrieve current validation configuration.

333

334

```javascript { .api }

335

/**

336

* Get demanded options configuration

337

* @returns Object containing required options

338

*/

339

getDemandedOptions(): Dictionary<string | undefined>;

340

341

/**

342

* Get demanded commands configuration

343

* @returns Object containing command requirements

344

*/

345

getDemandedCommands(): Dictionary<{ min: number; max: number; minMsg?: string; maxMsg?: string }>;

346

347

/**

348

* Get deprecated options configuration

349

* @returns Object containing deprecated options and their messages

350

*/

351

getDeprecatedOptions(): Dictionary<string | boolean | undefined>;

352

353

/**

354

* Get current strict mode settings

355

* @returns Whether strict mode is enabled

356

*/

357

getStrict(): boolean;

358

359

/**

360

* Get strict commands setting

361

* @returns Whether strict commands mode is enabled

362

*/

363

getStrictCommands(): boolean;

364

365

/**

366

* Get strict options setting

367

* @returns Whether strict options mode is enabled

368

*/

369

getStrictOptions(): boolean;

370

```

371

372

**Usage Examples:**

373

374

```javascript

375

const yarg = yargs()

376

.demandOption('config')

377

.strict()

378

.deprecateOption('old', 'Use new instead');

379

380

console.log('Required options:', yarg.getDemandedOptions());

381

console.log('Strict mode:', yarg.getStrict());

382

console.log('Deprecated options:', yarg.getDeprecatedOptions());

383

```

384

385

## Types

386

387

```javascript { .api }

388

/**

389

* Validation function type

390

*/

391

type ValidationFunction = (argv: Arguments, options: Options) => any;

392

393

/**

394

* Options object containing parser configuration

395

*/

396

interface Options {

397

alias: Dictionary<string[]>;

398

array: string[];

399

boolean: string[];

400

choices: Dictionary<string[]>;

401

config: Dictionary<Function | boolean>;

402

configObjects: Dictionary[];

403

configuration: Configuration;

404

count: string[];

405

defaultDescription: Dictionary<string | undefined>;

406

demandedCommands: Dictionary<{

407

min: number;

408

max: number;

409

minMsg?: string | null;

410

maxMsg?: string | null;

411

}>;

412

demandedOptions: Dictionary<string | undefined>;

413

deprecatedOptions: Dictionary<string | boolean | undefined>;

414

hiddenOptions: string[];

415

key: Dictionary<boolean | string>;

416

local: string[];

417

normalize: string[];

418

number: string[];

419

showHiddenOpt: string;

420

skipValidation: string[];

421

string: string[];

422

}

423

```