Skip to content

Feat: validate function should provide values as 2nd argument #273

Open
@alexilyaev

Description

@alexilyaev

Problem

Prompts chain of Start/End dates, End date should not be before Start date.

const responses = await prompts([
  {
    type: 'date',
    name: 'startDate',
    message: 'Start Date',
    initial: new Date(),
  },
  {
    type: 'date',
    name: 'endDate',
    message: 'End Date',
    initial: new Date(),
    validate(date) {
      // `endDate` should not be before `startDate`
    },
  },
]);

Solution

  {
    type: 'date',
    name: 'endDate',
    message: 'End Date',
    initial: new Date(),
    validate(date, values) {
      return date >= values.startDate || 'End Date should not be before Start Date';
    },
  },

Describe alternatives you've considered

Multiple prompts or onSubmit hacks as mentioned in #2.
If we already have validate, makes sense to allow access to previous answers.

I was also thinking about min and max values that could make sense (additionally)...
e.g. Once startDate is selected, endDate could have min: (prev, values) => values.startDate and then the user can't select a date before that date.

Additional context

Maybe it makes sense, for consistency, to add prompt as the 3rd argument, just like some of the other props https://github.com/terkelg/prompts#-prompt-objects. Though I'm not sure what would be the use case for that.
Btw, format doesn't get prompt as a 3rd argument but the docs in the same section say:

The function signature is (prev, values, prompt)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions