Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent users from typing special characters in textbox [duplicate]

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");
like image 780
Josh C Avatar asked Mar 15 '23 13:03

Josh C


2 Answers

You could use LINQ:

if (!TXT_NewPassword.Text.All(allowedchar.Contains))
{
    // Not allowed char detected
}
like image 77
Dmitry Avatar answered Apr 06 '23 07:04

Dmitry


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.");
    }
}
like image 44
David Carrigan Avatar answered Apr 06 '23 06:04

David Carrigan