Professional Documents
Culture Documents
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.
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(); } }
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(); } } }
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 }