leimelson06
leimelson06

Reputation: 39

How to disable Special Characters and Number in textbox?

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

Upvotes: 0

Views: 2110

Answers (1)

Ian
Ian

Reputation: 30813

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
}

Upvotes: 4

Related Questions