AlecAivazis / survey

A golang library for building interactive and accessible prompts with full support for windows and posix terminals.
MIT License
4.08k stars 350 forks source link

How to validate combinations of a multiselect? #197

Closed gowthamsadasivam closed 5 years ago

gowthamsadasivam commented 5 years ago

Hello,

I'm trying to validate a multiselect answer. For example one cannot have few combinations together as an answer. Currently, I'm doing it by a separate validation function in combination with an infinite for loop as below:

selected := []string{}
for {
    selected = []string{}
    prompt := &survey.MultiSelect{
        Message: "Select you choices: ",
        Options: []string{"A", "B1", "B2", "C", "D", "E1", "E2"},
    }
    survey.AskOne(prompt, &selected, nil)
    if selectValidator(selected) {
        break
    }
    fmt.Println("Please select only one of the B1 or B2 / E1 or E2")
}

This will prompt the question again if the multiselect answer contains the combination of E1 & E2 together or B1 & B2 together by the validator function selectValidator().

I would like to know how to achieve this using the survey.AskOne(prompt, &selected, nil) Validator parameter.

gowthamsadasivam commented 5 years ago

This code worked.

survey.AskOne(prompt, &selected, func(in interface{}) error {
            slist := in.([]string)
            if !selectValidator(slist) {
                return errors.New("Validation Failed!")
            }
            return nil
        })