4

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");
Josh C
  • 57
  • 1
  • 1
  • 6
  • Just an FYI, `TextBox`'s `Text` property is a `string`. You don't need to call `myTextbox.Text.ToString()`. It's redundant. – sab669 Oct 08 '15 at 14:21

5 Answers5

6

You could use LINQ:

if (!TXT_NewPassword.Text.All(allowedchar.Contains))
{
    // Not allowed char detected
}
Dmitry
  • 13,797
  • 6
  • 32
  • 48
1

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.");
    }
}
David Carrigan
  • 751
  • 1
  • 8
  • 21
0

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");
El Marce
  • 3,144
  • 1
  • 26
  • 40
0

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.

Callum Bradbury
  • 936
  • 7
  • 14
  • It's extremely illogical to speciffy the list of non-allowed characters, instead of the allowed ones. Just imagine having 65536 possible characters to validate on a 16bit character length. Not to mention it'd be a tragedy performance wise. – Tarec Oct 08 '15 at 14:41
  • Well, it depends what you're allowing or not allowing really, your assumption that people will always want to ban the majority of characters is *highly* illogical. Doesn't take a brain surgeon to switch it from banned to allowed, and I assume people asking these questions are at least vaguely capable of problem solving. It's also worth mentioning that the question specifically states it's to prevent users from typing 'special' characters, if they're special they're the ones that should be defined, not all the rest of them. Basically what I'm saying is you're wrong Mr Vulcan. – Callum Bradbury Oct 08 '15 at 15:01
0

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.

David Carrigan
  • 751
  • 1
  • 8
  • 21
  • User may paste into field, so I think checking in `TextChanged` or checking when we need to check is better solution. – Reza Aghaei Oct 08 '15 at 14:38
  • I had forgot about that, you're absolutely right @RezaAghaei Thinking about it, to take this approach and cover every possibility could get ugly and become tough to maintain. – David Carrigan Oct 08 '15 at 14:40