C
C#2y ago
js

char.IsLetterOrDigit

does a whitespace count as letter or digit
7 Replies
js
jsOP2y ago
im trying to write a statement to check if a string contains only alphanumeric characters an example would be Fast Food Emporium
MODiX
MODiX2y 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
MODiX2y 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.
Dellibrov
Dellibrov2y ago
Looks like neither of them
js
jsOP2y ago
if ((nameCheck.Any(char.IsLetterOrDigit) == false) || (nameCheck.Length > 5)) thats what ive got but spaces are flagging it as false for valid names
Dellibrov
Dellibrov2y ago
You could .Trim() i guess
char.IsWhiteSpace(' ')
char.IsWhiteSpace(' ')
Pobiega
Pobiega2y 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?