Text box validation using C#.

Masked textbox supports a declarative syntax for accepting or rejecting user input. To validate user input we have to use some additional mechanism like JavaScript/jQuery or server side validation. But we can do the same without using any of these mechanism. To perform this job we can use “KeyPress” event of TextBox.

Textbox’s Key Press event occurs when the control has focus and user press and releases a key. It has following format that is in C# language:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
}

 

The parameter e provides the data for this event which is of type KeyPressEventArgs. Char class has some in-built functions for checking the pressed and released key by user.

char.IsDigit(): whether the character is decimal digit or not.
char.IsLetter(): whether the character is a letter.
Char.IsLetterOrDigit(): whether the character is letter or digit.

To restrict the user from entering the digit in textbox:

if (char.IsDigit(e.KeyChar))
e.Handled = true;

 

Here e.Handled will tell the debugger that I have handled this event. We can use desired method to prevent specified type of key by the user.

To restrict both the letter and digit to be inputted by the user in c# language:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsLetterOrDigit(e.KeyChar) || char.IsDigit(e.KeyChar))
e.Handled = true;
}

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s