Accept only numeric and float values in TextBox in Windows Application using Regular Expression

Last Reply on May 03, 2018 12:44 AM By dharmendr

Posted on May 03, 2018 12:19 AM

Hello I want to do validations in windows form, how to do it ?

can we use javascript validations  in windows form ?

 

I want to do validation : for textboxmust accept int number / float number only.

 

Thanks

Posted on May 03, 2018 12:44 AM Modified on on May 03, 2018 12:45 AM

Hi ashishk,

You can use RegularExpressions for validation.

Check this example. Now please take its reference and correct your code.

For this example i have used TextBox KeyUp event. You can change it as per your requirement.

Form Design

Code

C#

private void txtNumber_KeyUp(object sender, KeyEventArgs e)
{
    if (txtNumber.Text.Length > 0)
    {
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^(?=.)([+-]?([0-9]*)(\.([0-9]+))?)$");
        System.Text.RegularExpressions.Match match = regex.Match(txtNumber.Text);
        if (match.Success)
        {
            MessageBox.Show("Valid");
        }
        else
        {
            MessageBox.Show("Invalid");
        }
    }
}

VB.Net

Private Sub txtNumber_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs)
    If txtNumber.Text.Length > 0 Then
        Dim regex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("^(?=.)([+-]?([0-9]*)(\.([0-9]+))?)$")
        Dim match As System.Text.RegularExpressions.Match = regex.Match(txtNumber.Text)
        If match.Success Then
            MessageBox.Show("Valid")
        Else
            MessageBox.Show("Invalid")
        End If
    End If
End Sub

Screenshot