0

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.

enter image description here

6
  • 2
    Depends on how you define "special character". Commented Mar 5, 2016 at 1:56
  • all characters that are not A-Z, a-z and Space Commented Mar 5, 2016 at 2:08
  • 1
    What if my name is Renée Nyström? Or 田中太郎? Commented 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. Commented Mar 5, 2016 at 2:30
  • 1
    Your local area has zero foreign people living there...? Commented Mar 5, 2016 at 2:31

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

5 Comments

How do i use this? for example my txtbox name is FN?
and it says ) expected
@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.
Thank you. You really helped me.
@leimelson06 no problem! glad that I can be of any help. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.