You are on page 1of 3

Chapter 4: Validation Form

Validation is a means to check the accuracy and correctness of the data entered by a user in an application. Validation can be performed for various checks such as checking the date entry for the correct format, checking a number field for proper range, and checking a string field for appropriate length. By performing validation, you can prompt the user to enter correct data and therefore, reduce errors. Otherwise a lot of resources would be wasted in fixing errors.

1. Validation by using Validating event of the control


To validate data in a control, the Validating event of that control can be used. The Validating event enables you to prevent the user from shifting focus from the control being validated to another control on the form until validation has been completed. Example:

Validation of the form:

User name should not be left blank Password length must be greater than 5

private void txtUserName_Validating(object sender, CancelEventArgs e) { if (txtUserName.Text.Trim()=="") { MessageBox.Show("User Name should not be left blank"); txtUserName.Focus(); } } private void txtPassWord_Validating(object sender, CancelEventArgs e) { if (txtPassWord.Text.Trim().Length<=5) { MessageBox.Show("Password length must be greater than 5"); txtPassWord.Focus(); } }

2. Validation by using manually coding

private bool ValidateData() { if (txtUserName.Text.Trim() == "") { MessageBox.Show("User Name should not be blank"); txtUserName.Focus(); return false; } if (txtPassWord.Text.Trim().Length < 5) { MessageBox.Show("Password length must be greater than 5"); txtPassWord.Focus(); return false; } return true; } private void btnLogin_Click(object sender, EventArgs e) { //if data is not valid, then return if (!ValidateData()) return; if (txtUserName.Text == "admin" && txtPassWord.Text == "password") { MessageBox.Show("Welcome"); } else { counter++; if (counter < 3) { MessageBox.Show("Login failed"); } else { MessageBox.Show("You have logged in failed three times."); Application.Exit(); } } }

3. Validation by using ErrorProvider control


Ko ErrorProvider control vo form Login. Mc nh l 1 errorProvider c dng cho tt c cc control trn form. bo li bng ErrorProvider dng hm SetError errorProvider1.SetError(controlName, "Error Message"); v d: errorProvider1.SetError(txtUserName, "User Name should not be blank");

private bool ValidateData() { errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink; bool result = true; if (txtUserName.Text.Trim() == "") { errorProvider1.SetError(txtUserName, "User Name should not be blank"); result = false; } else errorProvider1.SetError(txtUserName, ""); if (txtPassWord.Text.Trim().Length < 5) { errorProvider1.SetError(txtPassWord, "Password length must be greater than 5"); result = false; } else errorProvider1.SetError(txtPassWord, ""); return result; } private void btnLogin_Click(object sender, EventArgs e) { if (!ValidateData()) return; //do something }

You might also like