I need to validate a password entry on a textbox, I have a few demands to fullfill in order to allow the user profile to be created and one of them is to refuse registration if the password contains anything else different than numbers and the alphabet letters the system needs to deny the entry, everything I tried seems to fail. Here is where I'm standing right now:
private void BUT_Signup_Click(object sender, EventArgs e)
{
string allowedchar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
if (!(TXT_NewPassword.Text.ToString().Contains(allowedchar)))
MessageBox.Show("No special characters on the password are allowed");
You could use LINQ:
if (!TXT_NewPassword.Text.All(allowedchar.Contains))
{
// Not allowed char detected
}
Another suggestion as others have mentioned but not demonstrated.
Regular expression can achieve this as well.
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Invalid password. Password cannot be empty.");
return;
}
System.Text.RegularExpressions.Regex regex = null;
regex = new System.Text.RegularExpressions.Regex("^([a-zA-Z0-9])*$");
if (regex.IsMatch(textBox1.Text))
{
MessageBox.Show("Valid password.");
}
else
{
MessageBox.Show("Invalid password. Password cannot contain any special characters.");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With