Friday, October 14, 2011

Validation in windows application in C#

Whenever we create an application, some forms need specific entries. For example, phone numbers must be all numeric, whilst email ID must have a @ symbol followed somewhere by a . symbol. For these purposes, no automatic validators are provided for windows applications. Hence, we must manually give validations to these fields.

There are many logical routes to valication. The following is the validation code that I follow. Hope it helps you too. In case of any doubts or suggestions, kindly feel free to comment or mail me at nardz07@gmail.com.




Personally I find it best to write my validation code in the keypress event of a textbox, as it simply prevents the textbox from accepting any value that is outside the parameter for entry.

Let us first study the numeric validation. It must accept only numeric values, and not any alphabets or special characters. The following is my code for the keypress event of home phone number textbox:


 private void txthmno_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
                    {
                        e.Handled = true;
                    }
            }
            catch
            {


            }
        }


Here, I have used the if conditional statement... which translates to - If the key pressed is not a control key, AND not a digit key, then capture it as an exception and handle it. Otherwise, allow the keypress to be read in the textbox.


Now, say I need someone to enter their name, and no special characters. Then in that case, I must ensure that only alphabets are allowed. Here, I have implemented this in the keypress event for the first name textbox:


private void txtfrstnm_KeyPress(object sender, KeyPressEventArgs e)
        {
                    if (!char.IsControl(e.KeyChar) && !char.IsLetter(e.KeyChar))
                    {
                        e.Handled = true;
                    }
        }


In this case I simply replaced IsDigit with IsLetter... so unless the key pressed is a control key (enter or backspace or delete) or an alphabet, the textbox will not accept a value.

Now let us take another custom scenario, a little different than this. Say you are creating an application that must be able to read an email entry and tell whether it is a valid address or not. Clearly we cannot tell that without running through the databases of the said email distributor's server. However, email IDs in general have a format, and we can set a validation to ensure those requirements are met. Again, there is not a word limit or a restriction to any general set of characters, so we cannot simply disable certain keystrokes. What we can do however, is raise error dialogs.

This is a sample of what I did when I tried out an email entry textbox validation. I use the validating event of the text box, so the error will not be raised till we leave the textbox:

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    Regex regex = new Regex("@([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})");
    if (regex.IsMatch(textBox1.Text))
    {
        errorProvider1.SetError(textBox1, String.Empty);
    }
    else
    {
        errorProvider1.SetError(textBox1,
              "This is not valid date");
    }
}
.

As you might have noticed, we have used a concept called regex, which stands for regular expression. Regular expression is a concept that, simply put, lists out exactly what all characters are allowed.


For your knowledge, here is the regex for:


Date:

(?<Month>\d{1,2})/(?<Day>\d{1,2})/(?<Year>(?:\d{4}|\d{2}))

Phone Number:

\((?<AreaCode>\d{3})\)\s*(?<Number>\d{3}(?:-|\s*)\d{4})

 Email ID:

 ([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})

You might have noticed that I have preceded the regular expression with an @ symbol. This is because, regular expression is, by default a concept oriented in VB. To make it compatible in C#, where this code was written, we add a @ symbol.

The concept behind the validating and the validated events is the use of a concept called error provider. It is one control that sits in the background of the application and helps raise errors. But more on that later. For now, adieu.

No comments:

Post a Comment