For example in my form I will need to input my name in a textbox but when there's a special character or number in a textbox or a number, a messagebox will pop up saying that "Please type a valid name" after pressing the button.
-
2Depends on how you define "special character".Matti Virkkunen– Matti Virkkunen2016-03-05 01:56:15 +00:00Commented Mar 5, 2016 at 1:56
-
all characters that are not A-Z, a-z and Spaceleimelson06– leimelson062016-03-05 02:08:13 +00:00Commented Mar 5, 2016 at 2:08
-
1What if my name is Renée Nyström? Or 田中太郎?Matti Virkkunen– Matti Virkkunen2016-03-05 02:12:10 +00:00Commented Mar 5, 2016 at 2:12
-
Wow I didn't think about that but I will make a local application where the peoples name are Alphabetical.leimelson06– leimelson062016-03-05 02:30:35 +00:00Commented Mar 5, 2016 at 2:30
-
1Your local area has zero foreign people living there...?Matti Virkkunen– Matti Virkkunen2016-03-05 02:31:11 +00:00Commented Mar 5, 2016 at 2:31
|
Show 1 more comment
1 Answer
To avoid it doing wrong recognition when someone enters a non-ASCII character but valid name (such as 田中太郎), you may need to really list down the special characters you don't want to include.
But to keep it simple, if what you mean by special characters are all other than white space and alphabet, then simply use built-in function char.IsLetter and char.IsWhiteSpace:
if (str.Any(c => !char.IsLetter(c) && !char.IsWhiteSpace(c))){
//invalid
} else {
//valid
}
If you want to check for some specific range of characters and not others given the above checking, simply put your additional checking in the //invalid part:
if (str.Any(c => !char.IsLetter(c) && !char.IsWhiteSpace(c))){
//possible invalid
if (some additional character range checking){
//valid case
} else {
//truly invalid
//add as many else if as you want
}
} else {
//valid
}
5 Comments
leimelson06
How do i use this? for example my txtbox name is FN?
leimelson06
and it says ) expected
Ian
@leimelson06 it should be triple closing parenthesis
))) instead of two )) now it should be OK. Get the str from your TextBox.Text, for example: string str = textBoxFullName.Text; or string str = FN.Text then you can apply the above checking.leimelson06
Thank you. You really helped me.
Ian
@leimelson06 no problem! glad that I can be of any help. :)
