4

I want to make a control, when I create a companyId, to not permit to create id with special characters like, (&), (/), (), (ñ), ('):

 If txtIdCompany.Text.Contains("&") Then
   // alert error message
 End If 

But I can't do this:

If txtIdCompany.Text.Contains("&", "/", "\") Then
       // alert error message
     End If 

How can I check more than one string in the same line?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Esraa_92
  • 1,558
  • 2
  • 21
  • 48
  • 4
    [`String.IndexOfAny()`](https://msdn.microsoft.com/en-us/library/system.string.indexofany(v=vs.110).aspx) – Alex K. Nov 24 '15 at 16:09
  • Possible duplicate of [VB.NET - Adding more than 1 string to .contains](http://stackoverflow.com/questions/2212719/vb-net-adding-more-than-1-string-to-contains) – CodingIntrigue Nov 24 '15 at 16:09
  • I put this answer because I don´t find the solution in other pages yet. thanks – Esraa_92 Nov 24 '15 at 16:11
  • 3
    What about other Unicode symbols or foreign characters? You probably want to use a *whitelist* of allowed characters rather than a *blacklist* of disallowed characters. – Michael Liu Nov 24 '15 at 16:11
  • 1
    I would suggest using a Regular Expression - similar to the one used here http://stackoverflow.com/questions/2788727/how-can-i-check-with-a-regex-that-a-string-contains-only-certain-allowed-charact – d-unit Nov 24 '15 at 16:12
  • You could also always create your own extension method as well. – John Paul Nov 24 '15 at 16:41

2 Answers2

7

You can use collections like a Char() and Enumerable.Contains. Since String implements IEnumerable(Of Char) even this concise and efficient LINQ query works:

Dim disallowed = "&/\"
If disallowed.Intersect(txtIdCompany.Text).Any() Then
    ' alert error message
End If

here's a similar approach using Enumerable.Contains:

If txtIdCompany.Text.Any(AddressOf disallowed.Contains) Then
    ' alert error message
End If

a third option using String.IndexOfAny:

If txtIdCompany.Text.IndexOfAny(disallowed.ToCharArray()) >= 0 Then
    ' alert error message
End If
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0
If txtIdCompany.Text.Contains("&") Or txtIdCompany.Text.Contains("\") Or txtIdCompany.Text.Contains("/") Then

   // alert error message

 End If 
Ric
  • 12,855
  • 3
  • 30
  • 36
Gi0rgi0s
  • 1,757
  • 2
  • 22
  • 31
  • 1
    precisely what I wanted was not to have to do that. Because in the example I put a few characters, but I need to put all of this: (&/\ñ´'+*~$áéíóú{}[]()¿?=#@%|<>:;ç), so if I have to put: txtIdCompany.Text.Contains("&") for each one, the code will be too long. But thanks anyway. – Esraa_92 Nov 24 '15 at 16:38