validName() Function Misbehaving

Monkey Forums/Monkey Programming/validName() Function Misbehaving

c.k.(Posted 2012) [#1]
Trying to validate user input, but it doesn't seem to want to work. Can somebody look at this and tell me what I've done wrong? Thanks!

[monkeycode]
Function validName:Bool( name:String )
Local validChars:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-"
Local good:Bool = True
' make sure all characters are found in validChars String
For Local t:Int = 0 to name.Length() - 1
good = good And validChars.Contains(name[t])
Next
Return good
End

' this should validate:
' vName = validName( "c.k.lester" )
' but it doesn't
[/monkeycode]


jpoag(Posted 2012) [#2]
String(name[t]) is your problem:

[monkeycode]
String(name[t]) ' Original
String( Int ) ' name[t] resolves to Integer
"Int" ' String(Int) prints the number, not the character[/monkeycode]

What you want is 'FromChar()'

[monkeycode]
good = good And validChars.Contains(String.FromChar(name[t]))[/monkeycode]

BTW, if you run into an invalid character, you can return false immediately:

[monkeycode]
Function validName:Bool( name:String )
Local validChars:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-"
' make sure all characters are found in validChars String
For Local t:Int = 0 to name.Length() - 1
If Not validChars.Contains(String.FromChar(name[t])) Then Return False
Next
Return True
End[/monkeycode]

You won't see any performance gains from such a small section of code, but it's a good habit to learn.


c.k.(Posted 2012) [#3]
James, thank you for the help! Workin' good now. :-)


Goodlookinguy(Posted 2012) [#4]
You should use a For-Until loop if you ever find yourself in a case where you need to write "something - 1".
[monkeycode]Function validName:Bool( name:String )
Local validChars:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.-"
' make sure all characters are found in validChars String
For Local t:Int = 0 Until name.Length()
If Not validChars.Contains(String.FromChar(name[t])) Return False
Next
Return True
End[/monkeycode]To is inclusive (>= or <=) whereas Until is exclusive (> or <).