Wednesday, January 01, 2014

Validation Using Regular Expressions on c# windows form

Regular expressions are great way to validate data provided by a user to the fields of a form. Suppose that a user should input an age rather than a name, or an address rather than a gender, you can use power of regular expressions to validate them. The following example creates a simple windows forms application that demonstrates the use of regular expression in validating each fields of a form. Create a new windows forms application and add the below Textbox as per given label names.

LabelTypeNameProperty Values
1TextBoxfirstNameTextBox
2TextBoxlastNameTextBox
3TextBoxageTextBox
4TextBoxgenderTextBox
5TextBoxaddressTextBox
6TextBoxzipCodeTextBox
7ButtonsubmitButtonTextSubmit

 Although we can use radio buttons for the Gender field, we will be using a text box to demonstrate validation of text using regular expressions. Double click the submitButton to generate an event handler for its Click event. Be sure to import System.Text for the StringBuilder class that we will use andSystem.Text.RegularExpressions for the Regex class.

using System.Text;
using System.Text.RegularExpressions;

We should also declare a StringBuilder and Regex members in our Program class.
private StringBuilder errors;
private Regex validator;
 Use the following code for the Click event handler of submitButton.
private void submitButton_Click(object sender, EventArgs e)
{
    if (AreFieldsValid())
    {
        //Do task here
    }
}
The following is the code for AreFieldsValid() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private bool AreFieldsValid()
{
    errors = new StringBuilder();
 
    //Validate First Name and Last Name
    validator = new Regex(@"^([A-Z][a-z]+)(\s[A-Z][a-z]+)*$");
 
    if (!validator.Match(firstNameTextBox.Text).Success)
        errors.AppendLine("First name is not in the proper format.");
 
    if (!validator.Match(lastNameTextBox.Text).Success)
        errors.AppendLine("Last name is not in the proper format.");
 
    //Validate Age
    validator = new Regex(@"^\d{1,2}$");
 
    if (!validator.IsMatch(ageTextBox.Text))
        errors.AppendLine("Invalid Age.");
 
    //Validate Gender
    validator = new Regex(@"^([M|m]ale|[F|f]emale)$");
 
    if (!validator.IsMatch(genderTextBox.Text))
        errors.AppendLine("Invalid Gender.");
 
    //Validate Address
    validator = new Regex(@"^[0-9]+(\s[a-zA-Z]+)+$");
 
    if (!validator.IsMatch(addressTextBox.Text))
        errors.AppendLine("Address is not in the proper format.");
 
    //Validate ZipCode
    validator = new Regex(@"^\d{4}$");
 
    if (!validator.IsMatch(zipCodeTextBox.Text))
        errors.AppendLine("Invalid zip code");
 
    if (errors.ToString() == String.Empty)
    {
        return true;
    }
    else
    {
        MessageBox.Show(errors.ToString(), "Validation Failed", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
 
        return false;
    }
}

No comments:

Post a Comment