How to validate text in textbox control in winforms?
I have a control, where user have to put string, like "13:55". I want to show MessageBox, when this value will be diffrent, than "XX:YY".
How to do it?
In asp.net it was so easy to make, but how to implement it on winforms?
-
this is not the same question. There are posts about WebForms (RequiredFieldValidator). Here is question about WinForms, and validating like RequiredFieldValidator works in WinForms.. :)whoah– whoah2012-10-12 20:16:33 +00:00Commented Oct 12, 2012 at 20:16
-
@DavidStratton - I agree with whoah - it looks like the linked question was improperly tagged.JDB– JDB2012-10-12 20:21:29 +00:00Commented Oct 12, 2012 at 20:21
4 Answers
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.)
1 Comment
There are three validation videos at http://windowsclient.net/learn/videos.aspx that will walk you through the whole process.
But using a Masked Textbox might be easier, depending on what you are collecting for data.
Heck, for what you're doing, you could be really safe and use two NumericUpDown controls and not have to deal with the validation at all.
Comments
You should take a look at C# Regex
Match match = Regex.Match(input, "^\d\d:\d\d$"));
if (!match.Success) MessageBox.Show("Error");
1 Comment
00:10 and ignore the leading 1 and trailing 0. You need to add begin and end of input anchors, like so: ^[0-9][0-9]:[0-9][0-9]$. Also, [0-9] is equivalent to \d and \d\d is equivalent to \d{2}.You could also use an ErrorProvider instead of popping up a messagebox. An example is available on msdn for the ErrorProvider class. Basically you subscribe to the Validated event
this.nameTextBox1.Validated += nameTextBox1Validated;
and then check if the value is valid
private void nameTextBox1Validated(object sender, EventArgs e) {
if(isNameValid()) {
// clear error
nameErrorProvider.SetError(nameTextBox1, String.Empty);
}
else {
// set some helpful message
nameErrorProvider.SetError(nameTextBox1, "Invalid value.");
}
}
private bool isNameValid() {
// The logic for determining if a value is correct
return nameTextBox1.Text == "hello";
}
the error provider can be created like this
ErrorProvider nameErrorProvider = new ErrorProvider();
nameErrorProvider.SetIconAlignment(nameTextBox1, ErrorIconAlignment.MiddleRight);
nameErrorProvider.SetIconPadding(nameTextBox1, 2);
nameErrorProvider.BlinkRate = 1000;
nameErrorProvider.BlinkStyle = ErrorBlinkStyle.AlwaysBlink;