C
C#10mo ago
js

char.IsLetterOrDigit

does a whitespace count as letter or digit
7 Replies
js
jsOP10mo ago
im trying to write a statement to check if a string contains only alphanumeric characters an example would be Fast Food Emporium
MODiX
MODiX10mo ago
Servator
REPL Result: Success
char.IsLetter(' ')
char.IsLetter(' ')
Result: bool
False
False
Compile: 247.642ms | Execution: 17.679ms | React with ❌ to remove this embed.
MODiX
MODiX10mo ago
Servator
REPL Result: Success
char.IsDigit(' ')
char.IsDigit(' ')
Result: bool
False
False
Compile: 291.154ms | Execution: 17.143ms | React with ❌ to remove this embed.
Servator
Servator10mo ago
Looks like neither of them
js
jsOP10mo ago
if ((nameCheck.Any(char.IsLetterOrDigit) == false) || (nameCheck.Length > 5)) thats what ive got but spaces are flagging it as false for valid names
Servator
Servator10mo ago
You could .Trim() i guess
char.IsWhiteSpace(' ')
char.IsWhiteSpace(' ')
Pobiega
Pobiega10mo ago
So your validation isn't just alphanumeric, its alphanumeric and spaces. so write your own helper method for that. Something like
public static bool IsAlphaNumericOrWhitespace(this char c) => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c);
public static bool IsAlphaNumericOrWhitespace(this char c) => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c);
should work, but you might want to restrict it to just spaces instead of any whitespace.

Did you find this page helpful?