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

ぐ巨炮叔叔 提交于 2019-12-06 01:44:58

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.");
    }
}

That will always fail because you're telling it to fail if none of the characters included are valid. What you want instead of your .Contains(allowedchar) is something like...

if( TXT_NewPassword.Text.ToString().Any(ch => bannedChars.Contains(ch)))
{
   MessageBox.Show("No special blah blah blah");
}

With bannedChars being a collection of all the characters that aren't allowed. That will go through every character in the password and show the messagebox if any of them are in the bannedChars list.

You can probably do something much neater with Regex but I don't want to spend all day looking up how Regex works again, so this is the best you'll get from me.

You are testing if the password contains the whole allowedchar string. You have to do it the other way around, you need to test if every char in the password is contained in the allowedchars.

Here is the pseudocode with the idea for the solution (is not C# but hopefully you will realize what you need to do):

    String password = myTextbox.Text;
    foreach ( Char s in password ) 
        if ( !allowedchar.contains(s) )
            MessageBox.Show("No special characters on the password are allowed");

Why not control this rather check afterwards?

    private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        if (e.KeyChar == (Char)Keys.Back || !allowedChar.Any(chr => chr == e.KeyChar))
        {
            e.Handled = true;
            return;
        }

        e.Handled = false;
    }

Just another suggestion..

UPDATE:

Theoretically this can now handle the user passing in their desired password but now includes the preferred answer above. Happening once there would be more efficient than this approach happening at each KeyPress.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!