Skip to content

Commit

Permalink
Add required option to input prompt (#1455)
Browse files Browse the repository at this point in the history
Co-authored-by: Simon Boudrias <admin@simonboudrias.com>
  • Loading branch information
mandryllo and SBoudrias committed Jul 1, 2024
1 parent 909e496 commit 8e6fdf1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
18 changes: 18 additions & 0 deletions packages/input/input.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,24 @@ describe('input prompt', () => {
expect(getScreen()).toMatchInlineSnapshot(`"? What is your name Mikey"`);
});

it('shows validation message if user did not provide any value', async () => {
const { answer, events, getScreen } = await render(input, {
message: `What's your favorite food?`,
required: true,
});

events.keypress('enter');
await Promise.resolve();
expect(getScreen()).toMatchInlineSnapshot(`
"? What's your favorite food?
> You must provide a value"
`);

events.type('Quinoa');
events.keypress('enter');
await expect(answer).resolves.toEqual('Quinoa');
});

it('handle editing the answer (properly tracks cursor position)', async () => {
const { answer, events, getScreen } = await render(input, {
message: 'What is your name',
Expand Down
7 changes: 5 additions & 2 deletions packages/input/src/index.mts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@ import type { PartialDeep } from '@inquirer/type';
type InputConfig = {
message: string;
default?: string;
required?: boolean;
transformer?: (value: string, { isFinal }: { isFinal: boolean }) => string;
validate?: (value: string) => boolean | string | Promise<string | boolean>;
theme?: PartialDeep<Theme>;
};

export default createPrompt<string, InputConfig>((config, done) => {
const { validate = () => true } = config;
const { required, validate = () => true } = config;
const theme = makeTheme(config.theme);
const [status, setStatus] = useState<string>('pending');
const [defaultValue = '', setDefaultValue] = useState<string>(config.default);
Expand All @@ -38,7 +39,9 @@ export default createPrompt<string, InputConfig>((config, done) => {
if (isEnterKey(key)) {
const answer = value || defaultValue;
setStatus('loading');
const isValid = await validate(answer);

const isValid =
required && !answer ? 'You must provide a value' : await validate(answer);
if (isValid === true) {
setValue(answer);
setStatus('done');
Expand Down

0 comments on commit 8e6fdf1

Please sign in to comment.