C# Validating input for textbox on winforms
Description
There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating
event.
The Validating
event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true
the TextBox doesn't lose the focus.
MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order
Enter
GotFocus
Leave
Validating
Validated
LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
Sample Validating Event
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}
Update
You can use the ErrorProvider
to visualize that your TextBox is not valid.
Check out Using Error Provider Control in Windows Forms and C#
More Information
- MSDN - Control.Validating Event
- MSDN - ErrorProvider Component (Windows Forms)
- Using Error Provider Control in Windows Forms and C#
How to validate textboxes in C#.net winforms
If you have a very specific validation to do, Marc's answer is correct. However, if you only ensure the "enter number instead of letters" or "enter letters instead of numbers" thing, a MaskedTextBox would do the job better than you (user wouldn't be able to answer incorrect data, and you can still warn them by handling the MaskInputRejected event)
http://msdn.microsoft.com/en-us/library/kkx4h3az(v=vs.100).aspx
Textbox validation in C# Winforms - Should allow only numerics between 1-100
Use NumericUpDown
instead of normal TextBox
box with validation.
A NumericUpDown control contains a single numeric value that can be
incremented or decremented by clicking the up or down buttons of the
control. The user can also enter in a value, unless the ReadOnly
property is set to true.
You can specify the minimum and maximum numbers, it will allow the user to enter numbers between 1 and 100 and also let them use up and down buttons.
EDIT: If you want to do it through code then you can try something like in KeyPress
event of your TextBox
:
private void yourTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
The above can be improved to access .
for decimal numbers, but I guess you got the idea.
Validation textbox in winforms
Check out the MaskedTextBox if you don't want to have to validate in the first place.
var l_control = new MaskedTextBox();
l_control.Mask = "00\:00";
If you want to make the first digit optional:
l_control.Mask = "90\:90";
Otherwise, you could use a regular expression. 4 digits separated by a colon would be: @"^\d{2}:\d{2}$"
. (The @
symbol prevents C# from treating '\' as an escape character - nothing unique to regex.)
MessageBox Within A WinForms TextBox Validating Event Handler
In response to @adriano-repetti comment and some additional testing I removed the prompt from the validation event. The full solution I used was to create an additional property of bool?
that can be checked if blank values are allowed, disallowed, or undefined. If either disallowed or undefined the validation fails if the value is blank. If the validation fails due to a blank value and the new IsBlankValueAllowed property a prompt is displayed to ask the user to confirm this behavior. I decided to use a Property instead of data within a Tag property since it felt less 'hacked'.
Validating user input / Give .NET controls status OK or NOK
You have some useful facilities in windows forms to perform validation and show error messages including:
IDataErrorInfo
InterfaceValidating
Event of ControlsErrorProvider
ComponentValidateChildren
Method andAutoValidate
Property of Form
Using above options:
- You can perform validation when you are using data-binding to model classes.
- You van perform validation when you don't use data-binding.
- You can show error messages and an error icon near the controls which are in invalid states.
- You can decide to prevent the focus change from invalid controls or let the focus change.
- You can show a validation summary for your form.
- You can also apply DataAnnotations Validations in Windows Forms
IDataErrorInfo Interface
In cases which you have some model classes, the best fit for validation and providing error messages in windows forms is implementing IDataErrorInfo
. It's supported by data-binding mechanisms and some windows forms control like DataGridView
and ErrorProvider
.
To keep things simple you can write validation rules in your class and return error messages using IDataErrorInfo
properties. Even if you want to apply a more advanced scenario like using validation engines, at last it's better to implement IDataErrorInfo
to gain most consistency with widows forms.
You will use an ErrorProvider
to show error messages. It's enough to bind it to your data source and it shows errors automatically.
Validating Event of Controls
In cases that you don't have model classes and all validations should be done against controls, the best option is using Validating
event of controls. There you can set e.Cancel = true
to set the control state as invalid. Then you can prevent focus change or use the state of control in getting validation summary.
In this case you will use an ErrorProvider
to show errors. It's enough to set an error for a control in Validating
event this way: errorProvider1.SetError(control1, "Some Error")
or you can set an empty error message to remove validation error.
ErrorProvider Component
In both cases when you use databinding or when you use Validating
event, as mentioned above, ErrorProvider
shows and error icon with a tooltip that shows error message for you near the controls. (DataGridView
uses its own mechanism to show errors on rows and cells, without using an ErrorProvider
.)
You can also use the component to get a validation summary for your form using GetError
method of the component which return the error message of each control.
ValidateChildren Method and AutoValidate Property of Form
You can use ValidateChildren
method of form or your container control to check if there is a validation error for your controls or not.
Based on the value of AutoValidate
property of your form, it prevents focus change or let the focus change from invalid controls.
WinForm validation does not validate when button clicked
Try this pattern for validation
private bool ValidateChildren()
{
bool IsValid = true;
// Clear error provider only once.
usrError.Clear();
//use if condition for every condtion, dont use else-if
if (string.IsNullOrEmpty(usrTxtBox.Text.Trim()))
{
usrError.SetError(usrTxtBox, "field required!");
IsValid =false;
}
if (!Regex.IsMatch(usrTxtBox.Text, "</REGEX PATTERN/>"))
{
usrError.SetError(usrTxtBox, "</ERROR MESSAGE/>");
IsValid =false;
}
return IsValid ;
}
and int the button Click:
private void rgstr_Click(object sender, EventArgs e)
{
if (ValidateChildren())
{
// valid
}
else
{
//Error will shown respective control with error provider
}
}
How do I validate characters a user types into a WinForms textbox?
Rather than me writing the code for you, here are the basic steps required for accomplishing such a feat:
Handle the
KeyDown
event for yourTextBox
control.Use something like the
Char.IsSymbol
method to verify whether or not the character that they typed is allowed. Make sure you check explicitly for the underscore, because you want to allow it as a special case of other symbols.If a valid character is typed, do nothing. WinForms will take care of inserting it into the textbox.
However, if an invalid character is typed, you need to show the user a message, informing them that the character is not accepted by the textbox. A couple of things to do here:
Set the
e.SuppressKeyPress
property to True. This will prevent the character from appearing in the textbox.Display a tooltip window on the textbox, indicating that the character the user typed is not accepted by the textbox and informing them what characters are considered valid input.
The easiest way to do this is using theToolTip
class. Add this control to your form at design time, and display it when appropriate using one of the overloads of theShow
method.
In particular, you'll want to use one of the overloads that allows you to specify anIWin32Window
to associate the tooltip with (this is your textbox control).Alternatively, instead of a tooltip, you can display a little error icon next to the textbox control, informing the user that their last input was invalid. This is easy to implement using an
ErrorProvider
control. Add it to your form at design time, just like the tooltip control, and call theSetError
method at run-time to display an error message.Whatever you do, do not display a message box! That disrupts the user trying to type, and it's likely that they'll inadvertently dismiss it by typing the next letter they wanted to type.
Related Topics
Icecast 2: Protocol Description, Streaming to It Using C#
Routing: the Current Request for Action [...] Is Ambiguous Between the Following Action Methods
Built in .Net Algorithm to Round Value to the Nearest 10 Interval
Cannot Access a Disposed Object in ASP.NET Core When Injecting Dbcontext
How to Seed in Entity Framework Core 2
Getting/Setting File Owner in C#
How Is Performance Affected by an Unused Using Directive
Understanding .Asenumerable() in Linq to SQL
Authorization Header Is Lost on Redirect
How to Ensure a Form Displays on the "Additional" Monitor in a Dual Monitor Scenario
Use Xml Includes or Config References in App.Config to Include Other Config Files' Settings
How to Determine If a File Is Binary or Text in C#
Mobile Device Detection in ASP.NET
How to Remove All White Space from the Beginning or End of a String