Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
How to: Validate User Input in a Console Application

How to: Validate User Input in a Console Application 

Visual Studio 2005

You can create console applications that accept input parameter flags. During startup, when the user enters input to your console application, the common language runtime (CLR) presents an array of space-delimited input parameters to the main method.

You can use these parameters to control how your program operates. The following example is a console application that verifies that the user entered a first and last name at run time. The Maxlength field ensures that if the user entered a fictitious first name that is longer than 20 characters, the program throws an IllegalArgumentException. Your own application could also supply additional checks, such as verifying the length of the last name.

To validate user inputs

  1. On the File menu, point to New, and click Project.

  2. Click Console Application, and in the Name box, type ValidateUserInput.

  3. In the Program.jsl, replace the code with the following:

    package ValidateUserInput;
    public class Program
        public static void main(String[] args)
            int MaxLength = 20;
            if (args.length != 2)
                System.out.println("Usage: ValidateUserInput FirstName LastName ");
                System.out.println("For example:");
                System.out.println("ValidateUserInput John Doe");
            String input = new String(args[1]);
            if (input.get_Length() > MaxLength)
                 throw new IllegalArgumentException();
  4. In Solution Explorer, right-click the ValidateUserInput project name, and click Properties.

  5. Click Debug.

  6. In the Command line arguments text box, type in the command line arguments that you would normally use from the command prompt. For example: John Doe.

  7. Press F5 to compile and run your program.

    While your program is running in debug mode, Visual Studio automatically starts the application called ValidateUserInput, and supplies the two input parameters, such as John Doe. If you decide to run the application from a console window, you will need to type: ValidateUserInput John Doe.


To prevent buffer overruns and malicious attacks, your code should always verify user input content and length.

See Also

Community Additions

© 2015 Microsoft