Hi,
I have a textbox named fullnameTextbox. I want the user to only type letters in that textbox.I have a code for it but when there is a spacebar between 2 correctly typed words my error message pops up.How can i fix this?

Match matchMyRegex = Regex.Match(fullNameTextBox.Text, "^[a-zA-z]*$");

            if (!matchMyRegex.Success)
            {
                MessageBox.Show("Please insert only letters in FullName.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                fullNameTextBox.Focus();
               
            }

U need to add space in pattern and modified code is,

Match matchMyRegex = Regex.Match(fullNameTextBox.Text, "^[a-zA-z ]*$");

Edited 6 Years Ago by Renukavani: n/a

U need to add space in pattern and modified code is,

Match matchMyRegex = Regex.Match(fullNameTextBox.Text, "^[a-zA-z ]*$");

Another cool way to do this is prevent them from typing any other character than letters and space

(Do not forget to add your KeyPressEventHandler on your textbox)

protected void Sub Button3_KeyPress(Object sender,KeyPressEventArgs e)
{
	//Only allow letters and spaces/backspaces to be entered
       if(!char.IsLetter(e.KeyChar) && (char)e.KeyChar != 127 && (char)e.KeyChar != 8) e.Handled = true;
}

It might not work perfectly just translated on thefly from vb.net, but the idea is there :).

Just a note, if you want to be certain then use both methods...you can never be too careful with user input :p
One of the big flaws with the KeyPress approach shown above is that it wont fire if they paste a value (valid or otherwise) into the textbox.

How heavy your validation is should depend on the scale of damage an incorrect value can do.

This question has already been answered. Start a new discussion instead.