Page 1 of 1

Check if a string is valid *Updated!!!*

Posted: Wed Jan 25, 2006 4:44 pm
by josku_x
Code updated for 5.20+

Hello!

Here is a simple, but efficient snippet with that you can check if a string is valid :D .

Code: Select all

; String to validate:
String$="Example String [0_9] XyZ lOl"

; Validation rules:
Chars_AZ$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"  ; Alphabet (A-Z,a-z)
Chars_Num$="0123456789"                                           ; Numbers (0-9)
Chars_Special$=" !#/[]\_"                                         ; Special Characters

AlphaNumeric$=Chars_AZ$+Chars_Num$+Chars_Special$                 ; Alphanumeric (+Specials)

Procedure IsValidString(String$, Characters$)
  Static CountEx, ReturnVal
  CountEx=0
  For i=1 To Len(Characters$)
    CountEx+CountString(String$, Mid(Characters$, i, 1))
  Next
  If CountEx=Len(String$)
    ReturnVal=#True
  Else
    ReturnVal=#False
  EndIf
  ProcedureReturn ReturnVal
EndProcedure

Debug "String "+Chr(34)+String$+Chr(34)
If IsValidString(String$, AlphaNumeric$)
  Debug "Is a valid string."
Else
  Debug "Is not a valid string."
EndIf
Debug ""
Debug "Validation rule:"
For i=0 To Len(AlphaNumeric$) Step 27
  Debug "> "+Mid(AlphaNumeric$, i, 27-1)
Next
Usage:
IsValidString(String$, Characters$)
The String$ parameter is the string which will be validated, while the Characters$ parameter is a pattern for the allowed characters.
Example: IsValidString("Test", "tTes") checks if "Test" has any character of t, T, e or s.
EDIT: I updated the code so you could understand this a bit more easier.
Have fun!