3 Replies - 30304 Views - Last Post: 09 May 2009 - 02:49 PM Rate Topic: -----

#1 Gamok  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 09-May 09

Checking A String Contains Only Letters A - Z / Space

Post icon  Posted 09 May 2009 - 12:06 PM

So I basically want to make sure that a string entered by the user is valid. Valid being over 10 characters, containing only upper case characters, and only characters A - Z and spaces. The first two were easy, but I'm having trouble with the third, though.

What I originally attempted to do was create a loop which checks if the first invalid character is present with the InStr function, by using the characters ASCII value. The next ASCII value is then checked, and so on until it has checked the string for every single invalid character. If an invalid character gets picked up, 1 is added to a variable, and after the loop is finished executing, if the variable is no longer 0, invalid characters have been detected.

The way I've done it is probably massively overcomplicated, because it's checking for every invalid character. Is there an easier way to check if a string only contains certain acceptable characters, in this case A - Z and spaces?

Is This A Good Question/Topic? 0
  • +

Replies To: Checking A String Contains Only Letters A - Z / Space

#2 mark.bottomley  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 176
  • View blog
  • Posts: 990
  • Joined: 22-April 09

Re: Checking A String Contains Only Letters A - Z / Space

Posted 09 May 2009 - 12:44 PM

Since you know how to parse the string inot characters, you may want to look at Char.IsUpper, Char.IsLetter and Char.IsWhiteSpace and your own mixing logic. You can also use a loop to walk the string as I believe they all have a (String, Index) version of the functions
Was This Post Helpful? 0
  • +
  • -

#3 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2241
  • View blog
  • Posts: 9,412
  • Joined: 29-May 08

Re: Checking A String Contains Only Letters A - Z / Space

Posted 09 May 2009 - 01:43 PM

Or you can use a regular expression and do all three at once.
Was This Post Helpful? 0
  • +
  • -

#4 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1639
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Checking A String Contains Only Letters A - Z / Space

Posted 09 May 2009 - 02:49 PM

As pointed out by Adam I believe using Regular Expressions would be the best, most efficient way of accomplishing this. Here's an example of allowing only alpha characters (both upper and lower case) and spaces

Public Function isValid(ByVal str As String) As Boolean
	Dim pattern As String = "^[a-zA-Z\s]+$"
	Dim reg As New Regex(pattern)
	Return reg.IsMatch(str)
End Function



Hope that helps :)
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1