72

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

kemiller2002
  • 113,795
  • 27
  • 197
  • 251
MrM
  • 21,709
  • 30
  • 113
  • 139
  • If you write an extension method for strings, the check can be built in. You could also use one that's already written such as the [Extensions.cs](https://www.nuget.org/packages/Extensions.cs) NuGet package that makes it as simple as: For example: "abcXYZ123".IsAlphaNumeric() will return True whereas "abcXYZ123@".IsAlphaNumeric() will return False. By default spaces are ignored in .IsAlphaNumeric() but you can make spaces an invalid character thus: "abc 123".IsAlphaNumeric(false) which will return False. – Cornelius J. van Dyk Jan 22 '21 at 14:38

14 Answers14

115

In C# this is simple:

private bool HasSpecialChars(string yourString)
{
    return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
Matthew Young
  • 151
  • 1
  • 1
  • 12
prmph
  • 7,616
  • 11
  • 37
  • 46
  • 9
    Why isn't this answer upvoted ? Seems correct and quick to me. Way beter than diving into the regex world for such an easy problem – Marcello Grechi Lins Feb 04 '15 at 16:21
  • 2
    @MarcelloGrechiLins Regex is completely valid and likely faster when using a compiled Regex and re-using it across a large # of strings. As usual with software development there are trade-offs. :-) – Norman H Apr 21 '15 at 12:54
  • 1
    I would actually down vote this - with just minimal testing, it brings back true for \n, and I doubt anyone wants that. Regex at least will limit it to actual special chars. – Charles Feb 26 '16 at 10:13
  • 7
    @Charles Read the original question: "How do I check a string to make sure it contains numbers, letters, or space ONLY?" The code snippet fulfills the requirement. – prmph Feb 28 '16 at 06:34
  • 3
    It does. My bad, answered this and confused it with another post about getting only special characters. – Charles Feb 28 '16 at 06:39
  • this ignores backspace and del keypres – eomeroff Apr 12 '16 at 11:01
  • One issue with IsLetterOrDigit is that it is true also for umlaut/internanional characters (äåõ ...). So this is not equivalent to a-zA-Z0-9 -regex. – Pasi Savolainen Sep 07 '16 at 10:47
  • This failed in my case. – fletchsod Jul 22 '21 at 21:38
  • @prmph Can you please check the recent edit to this answer. I believe it significantly changes your original. – AdrianHHH Nov 01 '22 at 16:51
  • @AdrianHHH Yes, it is a significant change, but it fixes some syntax errors with my original answer – prmph Nov 02 '22 at 18:32
  • seems to ignore space characters – JoelFan Jan 11 '23 at 02:14
95

The easiest way it to use a regular expression:

Regular Expression for alphanumeric and underscores

Using regular expressions in .net:

http://www.regular-expressions.info/dotnet.html

MSDN Regular Expression

Regex.IsMatch

var regexItem = new Regex("^[a-zA-Z0-9 ]*$");

if(regexItem.IsMatch(YOUR_STRING)){..}
Community
  • 1
  • 1
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • 2
    I made this helper function for my utility class. Its working perfectly `public static bool ContainsOnlyAlphaNumericCharacters(this string inputString) { var regexItem = new Regex("^[a-zA-Z0-9 ]*$"); return regexItem.IsMatch(inputString); }` – vibs2006 Jun 26 '19 at 12:41
17

Try this way.

public static bool hasSpecialChar(string input)
    {
        string specialChar = @"\|!#$%&/()=?»«@£§€{}.-;'<>_,";
        foreach (var item in specialChar)
        {
            if (input.Contains(item)) return true;
        }

        return false;
    }
Emanuel Faisca
  • 205
  • 3
  • 9
17
string s = @"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c) 
                                            || Char.IsWhiteSpace(c)).ToArray());

if (s != withoutSpecial)
{
    Console.WriteLine("String contains special chars");
}
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
nan
  • 19,595
  • 7
  • 48
  • 80
7
String test_string = "tesintg#$234524@#";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
  // Good-to-go
}

An example can be found here: http://ideone.com/B1HxA

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
4

If the list of acceptable characters is pretty small, you can use a regular expression like this:

Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);

The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.

This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.

Berin Loritsch
  • 11,400
  • 4
  • 30
  • 57
3

Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:

[a-zA-Z0-9 ]
Chandu
  • 81,493
  • 19
  • 133
  • 134
2

You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:

using System;
using System.Linq;

namespace CheckStringContent
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get a password to check
            Console.WriteLine("Please input a Password: ");
            string userPassword = Console.ReadLine();

            //Check the string
            bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));

            //Write results to console
            Console.WriteLine($"Symbols are present: {symbolCheck}");     
        }
    }
}

This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.

2
private bool isMatch(string strValue,string specialChars)
    {
       return specialChars.Where(x => strValue.Contains(x)).Any();
    }
  • 1
    This answer is similar to other answers, but at the same quite different. Can you explain the difference, and how it is better? – joanis Nov 02 '21 at 14:46
  • sorry, i haven't tested its performance, it is just another way to solve the problem – Mumriz Khan Nov 08 '21 at 06:17
1

A great way using C# and Linq here:

public static bool HasSpecialCharacter(this string s)
{
    foreach (var c in s)
    {
        if(!char.IsLetterOrDigit(c))
        {
            return true;
        }
    }
    return false;
 }

And access it like this:

myString.HasSpecialCharacter();
stepheaw
  • 1,683
  • 3
  • 22
  • 35
1

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);
    }
roudlek
  • 160
  • 9
0

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23@".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
0

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

yourString.Any(char.IsLetterOrDigit);
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
0

No special characters or empty string except hyphen

^[a-zA-Z0-9-]+$
Ehsan Ehsani
  • 412
  • 3
  • 7