Home »
.Net »
C# Programs
C# - Username and Password Validation Program
In this example, we will learn how to validate the given username and password using C# program?
Submitted by Nidhi, on October 13, 2020 [Last updated : March 22, 2023]
Here, we will read the username and password from the user and check the conditions for validations.
C# program to validate the username and password
The source code to demonstrate the validation of username and password is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# - Username and Password Validation Program.
using System;
class Demo
{
public static int Main()
{
string username = "";
string password = "";
Console.Write("Enter Username(only 4 characters):");
username = Console.ReadLine();
Console.Write("Enter Password: (minimum 6 characters)");
password = Console.ReadLine();
if (username.Length != 4)
{
Console.WriteLine("Please enter correct username");
return -1;
}
else if (password.Length < 6)
{
Console.WriteLine("Please enter correct password");
return -1;
}
Console.WriteLine("Username: " + username);
Console.WriteLine("Password: " + password);
return 0;
}
}
Output
Enter Username(only 4 characters):abcd
Enter Password: (minimum 6 characters)Include@help
Username: abcd
Password: Include@help
Press any key to continue . . .
Explanation
Here, we created a class Demo that contains the Main() method. The Main() method is the entry point for the program, here we created two string variables username and password. Then we read the value of the username and password. Here, we checked the length of user and password for validation, if entered username and password is correct then print them on the console screen otherwise print the error message on the console screen.
C# Basic Programs »