Example : How to set the Password Character in the Password box in C#?
private void Form1_Load(object sender, EventArgs e)
{
TxtPass.PasswordChar = '*';
TxtCPass.PasswordChar = '*';
//TxtPass.UseSystemPasswordChar = true;
//TxtCPass.UseSystemPasswordChar = true;
}
Example: How to set up different types of Password Validation in the Password box in C#?
using System;
using System.Linq;
using System.Windows.Forms;
private bool ValidatePassword() //Function Creation
{
string password = TxtPass.Text;
// Password cannot be empty/blank
if (string.IsNullOrWhiteSpace(password))
{
MessageBox.Show("Please must enter Password.");
TxtPass.Focus();
return false;
}
// Length validation 8-20
if (password.Length < 8 || password.Length > 20)
{
MessageBox.Show("Password must be between 8 and 20 characters.");
TxtPass.Focus();
return false;
}
// Uppercase letter validation
if (!password.Any(char.IsUpper))
{
MessageBox.Show("Password must contain at least one uppercase letter.");
TxtPass.Focus();
return false;
}
// Lowercase letter validation
if (!password.Any(char.IsLower))
{
MessageBox.Show("Password must contain at least one lowercase letter.");
TxtPass.Focus();
return false;
}
// Number validation
if (!password.Any(char.IsDigit))
{
MessageBox.Show("Password must contain at least one number.");
TxtPassword.Focus();
return false;
}
// Special character validation
if (!password.Any(ch => !char.IsLetterOrDigit(ch)))
{
MessageBox.Show("Password must contain at least one special character.");
TxtPass.Focus();
return false;
}
// Space validation
if (password.Contains(" "))
{
MessageBox.Show("Password cannot contain spaces.");
TxtPass.Focus();
return false;
}
// Confirm Password validation
if (password != TxtCPass.Text)
{
MessageBox.Show("Password and Confirm Password do not match.");
TxtCPass.Focus();
return false;
}
return true;
}
//Now, call the above function 'ValidatePassword()' on Save Button Click Event as below.
private void BtnSave_Click(object sender, EventArgs e)
{
// Validate password
if (!ValidatePassword())
{
return;
}
// Now continue rest save or database code from here.
}
![]()
0 Comments