In this article I will explain with an example, how to perform US Mobile number validation using Regular Expressions in Windows Forms (WinForms) Application using C# and VB.Net.
 
 
Form Design
The following Form consists of:
TextBox – For capturing Mobile number.
Label – For showing error message.
Button – For validating US Mobile number.
US Mobile Number validation using Regular Expressions in C# and VB.Net
 
The Button has been assigned with the Click event handler.
US Mobile Number validation using Regular Expressions in C# and VB.Net
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Text.RegularExpressions;
 
VB.Net
Imports System.Text.RegularExpressions
 
 
Regular Expression (Regex) to validate US Mobile Number
Regular Expression (Regex)
^(\([0-9]{3}\)|[0-9]{3})[\s\-]?[\0-9]{3}[\s\-]?[0-9]{4}$
 
Explanation
Above Regular Expressions validates US Mobile number.
The following conditions must satisfy for a US Mobile number to be termed as valid.
1. It should be 10 digits long.
2. It may begin with an optional (.
3. After the optional (, it must be 3 digits. If it does not have a (, it must start with 3 digits.
4. It can have an optional) after first 3 digits.
5. It can have an optional hyphen (-) or empty space after ), if present or after first 3 digits.
6. Then there must be 3 more digits.
7. After second set of 3 digits, it can have another optional hyphen (-) or empty space.
8. Finally, it must end with four digits.
Valid examples: (308)-135-7895, 308-135-7895, 308135-7895, 3081357895, (308) 135 7895, 308 135 7895, 308135 7895
 
Example
When the Validate Button is clicked, the value of the TextBox is validated against the Regular Expressions (Regex) and if invalid, the error message is displayed.
C#
private void OnValidate(object sender, EventArgs e)
{
    lblError.Hide();
    Regex regex = new Regex(@"^(\([0-9]{3}\)|[0-9]{3})[\s\-]?[\0-9]{3}[\s\-]?[0-9]{4}$");
    if (!string.IsNullOrEmpty(txtUSMobile.Text.Trim()))
    {
        if (!regex.IsMatch(txtUSMobile.Text.Trim()))
        {
            lblError.Show();
        }
    }
    else
    {
        lblError.Text = "Mobile Number is required.";
        lblError.Show();
    }
}
 
VB.Net
Private Sub OnValidate(ByVal sender As Object, ByVal e As EventArgs) Handles btnValidate.Click
    lblError.Hide()
    Dim regex As Regex = New Regex("^(\([0-9]{3}\)|[0-9]{3})[\s\-]?[\0-9]{3}[\s\-]?[0-9]{4}$")
    If Not String.IsNullOrEmpty(txtUSMobile.Text.Trim()) Then
        If Not regex.IsMatch(txtUSMobile.Text.Trim()) Then
            lblError.Show()
        End If
    Else
        lblError.Text = "Mobile Number is required."
        lblError.Show()
    End If
End Sub
 
 
Screenshots
Invalid Value
US Mobile Number validation using Regular Expressions in C# and VB.Net
 
Valid Value
US Mobile Number validation using Regular Expressions in C# and VB.Net
 
 
Demo
US Mobile Number validation using Regular Expressions in C# and VB.Net
 
 
Downloads