Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
am trying to limit the types of characters that a textbox should allow for example it should only allow letters and numbers with at least one lower and one uppercase later but it should not allow symbols.

What I have tried:

I have not tried anything so far
C#

Posted
Updated 11-Jan-23 18:10pm
Comments
BillWoodruff 13-Jan-23 0:39am    
then try something, and come back with code and specific questions.

1 solution

Google Search is always a good place to start. I used: winform textbox specific characters - Google Search[^] and the first found was this solution: Only allow specific characters in textbox [solved] - StackOverflow[^]

UPDATE

To simplify the proposed solution in the link above, here is a simplified version of the accepted answer in the link provided. Only allows numerics, lower and upper case characters, and selected special characters. All other characters are ignored.
C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        textBox1.KeyPress += OnKeyPress;
    }

    private void OnKeyPress(object? sender, KeyPressEventArgs e)
    {
        // allow numerics
        if (e.KeyChar >= '0' && e.KeyChar <= '9')
            return;

        // allow lowercase characters
        if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
            return;

        // allow uppercase characters
        if (e.KeyChar >= 'A' && e.KeyChar <= 'Z')
            return;

        // allow backspace and other special characters in the string
        if ("\b".Contains(e.KeyChar))
            return;

        e.Handled = true;
    }
}

Here is a more compact version using Pattern Matching[^]:
C#
private void OnKeyPress(object? sender, KeyPressEventArgs e)
{
    e.Handled = e.KeyChar switch
    {
        >= '0' and <= '9' => false, // allow numerics
        >= 'a' and <= 'z' => false, // allow lowercase characters
        >= 'A' and <= 'Z' => false, // allow uppercase characters
        '\b' => false,              // allow backspace
        _ => true
    };
}
 
Share this answer
 
v7
Comments
BillWoodruff 13-Jan-23 0:38am    
voted #3 for response to gimme-codez OP who "haven't tried anything" on a question almost certain to be removed.

however, your reply is potentially helpful.
Graeme_Grant 13-Jan-23 1:20am    
I usually post code if there is no clear solution but this does what he asked.
BillWoodruff 13-Jan-23 1:36am    
and, it is your code ?
Graeme_Grant 13-Jan-23 1:50am    
Not mine, but as it is an accepted answer, and a brief read, it should work.

Do you have an alternative solution?
BillWoodruff 13-Jan-23 3:09am    
users will accept anything :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900