Kevin
Kevin

Reputation: 37

Check For Special Characters without using Regex

i m a newbie in C# code , i need help with validating special characters without using regex , can someone help me?

i m using this code ATM and want to make it works without regex

else if (Regex.IsMatch(textBox2.Text, "^[a-zA-Z ]+$")==false)
        {
            MessageBox.Show("Name may not contain any special characters");
        }

Thanks!

Upvotes: 1

Views: 1019

Answers (3)

manojlds
manojlds

Reputation: 301047

The regex solution isn't really bad, but if Regex is prohibited, you can do the following:

textBox2.Text.All(Char.IsLetter);

Update:

Since you want (space) too:

textBox2.Text.All(c => Char.IsLetter(c) || c == ' ');

Note that Char.IsLetter will return true for any Unicode letter. A more strict version would be:

textBox2.Text.All(c => (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c == ' '));

You get the idea. Basically, we go through all the characters and see if it is in the A-Z or the a-z range or a space.

Needs using System.Linq;. The same can be achieved using a simple loop too.

Upvotes: 2

Nicholas Carey
Nicholas Carey

Reputation: 74187

We'll, you can do that lots of different ways. For instance,

  • A positive test, using Linq makes things nice and declarative:

    public bool isValid( string s )
    {
      Func<char,bool> valid = c => { c == ' ' || ( c >= 'a' && c <= 'z' ) || ( c >= 'A' || c <= 'Z' ) } ;
      return s.All(valid) ;
    }
    
  • Ditto for a negative test using Linq

    public bool isInvalid( string s )
    {
      Func<char,bool> valid = c => { c == ' ' || ( c >= 'a' && c <= 'z' ) || ( c >= 'A' || c <= 'Z' ) } ;
      return s.Any(!valid) ;
    }
    
  • Linq won't necessarily be the fastest way to do this so you might to simply simply iterate over the string, old-school:

    public bool isValid( string s )
    {
      bool valid = true ;
      for ( int i = 0 ; valid  && i < s.Length ; ++i )
      {
        char c = s[i] ;
        valid = c == ' ' || ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ;
      }
        return valid ;
    }
    

Upvotes: 2

TGH
TGH

Reputation: 39248

You can probably loop through the string and compare the characters against ascii codes

How to get ASCII value of string in C#

Check if it's in the upper case and lower case ascii code ranges

Upvotes: 0

Related Questions