Reputation: 740
I am developing a Windows Form Application. One of my text box suppose to receive a numerical value for further processing. The input can be a round number or a number with a decimal point. If the user enters an invalid character other than a number, backspace key or a dot(".")
, A label with a warning will appear. This is my code:
private void TextBoxMainManualCpkVal_KeyPress(System.Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((!IsNumeric(e.KeyChar) && e.KeyChar != ControlChars.Back && e.KeyChar != "."))
{
LabelWarnMainCpk.Visible = true;
e.KeyChar = null;
}
else
{
LabelWarnMainCpk.Visible = false;
}
}
Now, I wanted to make sure if the user enters a funny numeric value such as "1.2.3"
The warning label shall show.
How Do I achieve this?
Upvotes: 0
Views: 158
Reputation: 127
For windows forms application you can use a masked input to be sure, that user can enter only that values which you allows him to enter by mask. Like this - 5 numbers, one dot, and two more numbers after
and it will looks like this in output:
Upvotes: 3
Reputation: 16277
Use Regex:
var regex = new Regex(@"^[0-9]([.,][0-9]{1,3})?$", RegexOptions.IgnoreCase);
var match = regex.Match(inputString);
bool isValid = match != null && match.Success;
An alternative solution found in stackoverflow:
bool IsDecimalFormat(string input) {
Decimal dummy;
return Decimal.TryParse(input, out dummy);
}
Upvotes: 0