简体   繁体   中英

How to restrict user input?

I want to restrict user input, so he can only type in 28,29,30 or 31.

I know that there is a way to do it by checking if the input is in an array of valid dates/day. Could someone explain me how can I do a check? For example if

int[] days = new int[4] {28, 29, 30, 31};

How can I do validation that will check if what user inputted is inside the array? What conditions should I set? I don't have a code to show since I do not know how to write that type of validation. If there is no way to do it how can restrict user with if statement that will restrict him to only these 4 numbers?

My code so far looks like that:

    int GetDaysInMonth()
    {
        const int MinDaysInMonth = 28;
        const int MaxDaysInMonth = 31;

        Console.WriteLine("How many days there are in your chosen month? [it needs to be 28, 30 or 31]");
        userInput = Console.ReadLine();

        while (!int.TryParse(userInput, out daysInMonth) || daysInMonth > MaxDaysInMonth || daysInMonth < MinDaysInMonth)
        {
            Console.WriteLine("Wrong input! Remember it needs to be 28, 30 or 31");
            userInput = Console.ReadLine();
        }
        Console.WriteLine();
        return daysInMonth;
    }

Thanks

If you are trying to check if an input is in an array of valid inputs you could use the .Contains() method.

public static bool IsValid(int input, int[] validInputs)
{
    return validInputs.Contains(input);
}

You could use it like below:

int input = 28;
int[] validInputs = new[] { 28, 29, 30, 31 };

bool result = IsValid(input, validInputs); //result is `true`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM