Hari
Hari

Reputation: 740

Detect invalid numbers in text box

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;
    }
}

Valid Case: Valid Input

Invalid Case: Invalid Input where I entered 1.2"w". Letter "w" is INVALID

Now, I wanted to make sure if the user enters a funny numeric value such as "1.2.3" The warning label shall show.

Currently: Invalid Input That Does Not Shows the warning label

How Do I achieve this?

Upvotes: 0

Views: 158

Answers (2)

Alexander Demichev
Alexander Demichev

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

enter image description here

and it will looks like this in output:

enter image description here

Upvotes: 3

David
David

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

Related Questions