Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check that a string doesn't include any characters other than letters and numbers?

This is what I have so far, but I can't find anywhere the code to say that I just want to include letters and numbers. I'm not familiar with regular expressions. Right now my code just ignores the while loop even if I include '#'.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    private void okBtn_Click(object sender, EventArgs e)
    {
        if(textBox1.Text.Contains(@"^[^\W_]*$"))
        {
            fm1.txtFileName = textBox1.Text;
            this.Close();
        }
        else
        {
            MessageBox.Show("Filename cannot include illegal characters.");
        }
    }
}
like image 357
liam.burns Avatar asked Feb 02 '26 04:02

liam.burns


2 Answers

You can use the method char.IsLetterOrDigit to check whether a input string only contains letters or digits:

if (input.All(char.IsLetterOrDigit))
{
    //Only contains letters and digits
    ... 
}
like image 197
cuongle Avatar answered Feb 03 '26 17:02

cuongle


As you're checking for invalid filenames, I'd use Path.GetInvalidPathChars instead:

char[] invalidChars = Path.GetInvalidPathChars();
if (!input.All(c => !invalidChars.Contains(c)))
{
    //invalid file name
like image 30
It'sNotALie. Avatar answered Feb 03 '26 18:02

It'sNotALie.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!