Windows Application - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Win App Validations

Windows Application Validations

shape Description

Validation means some set of rules, which one want to maintain for their application. One can allow users, if and only if they follow these rules or else they are not allowed to access the application. The "Key Events generation by using ASCII values of those keys and how to apply validations" are shown below.

shape Example

Follow the below simple example application to learn validations efficiently.

shape Step 1

Design the form as shown in the below figure.

shape Step 2

Write the following code to achieve above validations. [csharp] using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; namespace WindowsFormsApplication29 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnRegister_Click(object sender, EventArgs e) { if(txtName.Text!=""txtPassword.Text!=""txtEmail.Text!="") { if(txtPassword.Text.Length>=8)//Checks whether the password should have minimum 8 characters or not { MessageBox.Show("Successfully Registered"); } else { MessageBox.Show("Please enter minimum 8 charactrer for password", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Please enter the all fields ","ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void txtName_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back); } private void Form1_Load(object sender, EventArgs e) { } private void txtEmail_Leave(object sender, EventArgs e) { Regex mRegxExpression; if (txtEmail.Text.Trim() != string.Empty) { mRegxExpression = new Regex(@"^([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])$"); if (!mRegxExpression.IsMatch(txtEmail.Text.Trim()))//Checks whether the email id is in correct format or not { MessageBox.Show("E-mail address format is not correct", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); txtEmail.Focus(); } } } } } [/csharp]

shape Step 3

Press f5 to run the application. Then the following window will appear.

shape Step 4

Check all validations mentioned above. The following  figures show some errors if the user does not follow the rules.
  • If the user does not enter all the fields, then the error will appear as shown in the below figure.
  • If the user does not enter proper email id, then the error will appear as shown in the below figure.
  • If the user does not enter minimum 8 characters for the password field, then the error will appear as shown in the below figure.