简体   繁体   中英

Check for special characters (/*-+_@&$#%) in a string?

How do I check a string to make sure it contains numbers, letters, or space only?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

如何检查字符串以确保它仅包含数字,字母或空格?

Create a method and call it hasSpecialChar with one parameter and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection.

public void hasSpecialChar(string input)
    {
        char[] specialChar = {'(',')'};
        foreach (char item in specialChar)
        {
            if (input.Contains(item)) MessageBox.Show("it contains");
        }
    }

in your button click evenement or you click btn double time like that:

private void button1_Click(object sender, EventArgs e)
    {
       hasSpecialChar(textbox1.Text);
    }

如何检查字符串以确保它仅包含数字,字母或空格?

private bool isMatch(string strValue,string specialChars)
    {
       return specialChars.Where(x => strValue.Contains(x)).Any();
    }

Based on @prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):

yourString.Any(char.IsLetterOrDigit);

No special characters or empty string except hyphen

^[a-zA-Z0-9-]+$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM