代码之家  ›  专栏  ›  技术社区  ›  lucians

实时捕获用户输入错误

  •  0
  • lucians  · 技术社区  · 6 年前

    我制作了这个简单的控制台应用程序,它要求用户输入用户名和密码。 然后数据保存在数据库中。对于数据库中的每一列,我为数据类型分配了有限数量的值。例如,密码( varchar(5) )最多只能有5个字符。

    using System;
    
    namespace MyConto
    {
        public class NewUser
        {
            public static void NewUserRegistration()
            {
                Console.Write("Username: ");
                string user = Console.ReadLine();
    
                Console.Write("Password: ");
                string pass = Console.ReadLine();     
            }
        }
    }
    

    现在,我如何才能使一个实时的(??)检查用户在控制台中写入的内容?甚至有可能? 例如,如果用户在 "password" 作为密码,字符串太长。

    谢谢

    4 回复  |  直到 6 年前
        1
  •  1
  •   GPW    6 年前

    我想“实时”的意思是你 不要 希望用户在看到消息之前按Enter键-只要他们键入第6个字符,它就会告诉他们消息太长。不能使用console.readline()来执行此操作 能够 改为使用console.readkey()执行此操作,尽管这是一项很大的工作…但只是为了好玩:

    class Program
    {
        static void Main(string[] args)
        {
            //First clear the screen.  We need to have absolute knowledge of what's on 
            //the screen for this to work.
            Console.Clear();
            //hide the cursor as it has no real bearing on much....
            Console.CursorVisible = false;
            var user = GetLimitedInput("UserName?", 0, 10, true);
            var password = GetLimitedInput("Password?", 4, 5, false);
    
            Console.Clear();
            Console.WriteLine($"User is {user} and password is {password}");
        }
    
    
        private static string GetLimitedInput(string prompt, 
            int lineToShowPromptOn, int maxChars, bool showChars)
        {
            //set cursor to the suggested position
            Console.SetCursorPosition(0, lineToShowPromptOn);
            //output the prompt.
            Console.WriteLine(prompt);
            Console.SetCursorPosition(0, lineToShowPromptOn + 1);
    
            var finished = false;
            var inputText = string.Empty;
    
            while (!finished)
            {
                if (Console.KeyAvailable)
                {
                    //remembr old input so we can re-display if required.
                    var oldInput = inputText;
                    var key = Console.ReadKey();
                    //check for CTRL+C to quit
                    if (key.Modifiers.HasFlag(ConsoleModifiers.Control) && key.KeyChar=='c')
                    {
                        inputText = string.Empty;
                        finished = true;
                    }
                    //allow backspace
                    else if (key.KeyChar == '\b')
                    {
                        if (inputText.Length > 0)
                        {
                            inputText = inputText.Substring(0, inputText.Length - 1);
                        }
                    }
                    //check for return & finish if legal input.
                    else if (key.KeyChar == '\r')
                    {
                        if (inputText.Length<=maxChars)
                        {
                            finished = true;
                        }
                    }
                    else
                    {
                        //really we should check for other modifier keys (CTRL, 
                        //ALT, etc) but this is just example.
                        //Add text onto the input Text
                        inputText += key.KeyChar;
                    }
    
                    if (inputText.Length > maxChars)
                    {
                        //Display error on line under current input.
                        Console.SetCursorPosition(0, lineToShowPromptOn + 2);
                        Console.WriteLine("Too many characters!");
                    }
                    else
                    {
                        //if not currently in an 'error' state, make sure we
                        //clear any previous error.
                        Console.SetCursorPosition(0, lineToShowPromptOn + 2);
                        Console.WriteLine("                     ");
                    }
                    //if input has changed, then refresh display of input.
                    if (inputText != oldInput)
                    {
                        Console.SetCursorPosition(0, lineToShowPromptOn + 1);
                        //do we show the input?
                        if (showChars)
                        {
                            //We write it out to look like we're typing, and add 
                            //a bunch of spaces as otherwise old input may be        
                            //left there.
                            Console.WriteLine(inputText+"            ");
                        }
                        else
                        {
                            //show asterisks up to length of input.
                            Console.WriteLine(new String('*', inputText.Length)+"            ");
                        }
    
                    }
    
                }
            }
    
            return inputText;
        }       
    }
    

    注:这有很多缺陷,但只是为了说明原因:)

        2
  •  2
  •   apomene    6 年前

    添加验证方法,如:

    private bool isValid(string input)
    {
       //my validation logic
    }
    

    使用方式如下:

      ...
    string user = Console.ReadLine();
    if (!isValid(user))
    {
        ///my logic for warning the user that input is invalid
    }
    ...
    
        3
  •  1
  •   Konamiman    6 年前

    如果你想一直询问用户直到他给出有效密码,你可以这样做:

    string ObtainPassword()
    {
        string password;
        string passwordErrorMessage;
        while(true)
        {
            Console.Write("Password: ");
            password = Console.ReadLine();
            passwordErrorMessage = ValidatePassword(password);
            if (passwordErrorMessage == null)
                return password;
    
            Console.WriteLine($"\r\n*** {passwordErrorMessage}");
        }
    }
    

    密码验证方法如下:

    string ValidatePassword(string password)
    {
        if(password.Length > 5) return "Password is too long";
    
        //Add other validations here as needed
    
        return null;
    }
    
        4
  •  0
  •   lucians    6 年前

    最后我得到了:

    using System;
    
    namespace MyConto
    {
        public class NewUser
        {
            public static void NewUserRegistration()
            {
                Console.Write("Username: ");
                string user = Console.ReadLine();
    
                Console.Write("Password: ");
                string pass = Console.ReadLine();
                while (pass.Length > 5)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Insert a valid password (max 5 chars)\n");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("Password: ");
                    pass= Console.ReadLine();
                }     
            }
        }
    }