patterncsharpModerate
Input validation for text boxes in a Form
Viewed 0 times
boxestextvalidationinputforform
Problem
In a Win Form I'm doing initial validation in the Form. So before saving data, I want to validate whether all the required fields are filled (Text Boxes) by the user. There are about 18 such Text Boxes in the Form. Currently I'm doing it as follows. To make the code short only three fields are shown in the code.
Another option would be to use the logic inside the cmbSave_Click straightaway as follows,
Basically the code should be readable, consistent and should perform the validation properly.
Which option could be considered better? If both are not good please propose a way to do this?
private void cmbSave_Click(object sender, EventArgs e)
{
if(IsFilled (txtApplicationNumber.Text))
{
if(IsFilled (txtEmployeeID.Text))
{
if (IsFilled(txtNIC.Text))
Save(sender, e);
}
}
}
private bool IsFilled(string s)
{
if (s != "")
{ return true; }
else
{ return false; }
}Another option would be to use the logic inside the cmbSave_Click straightaway as follows,
private void cmbSave_Click(object sender, EventArgs e)
{
If (txtApplicationNumber.Text!="" & txtEmployeeID.Text!="" & txtNIC.Text="")
Save(sender, e)
}Basically the code should be readable, consistent and should perform the validation properly.
Which option could be considered better? If both are not good please propose a way to do this?
Solution
Another option would be to handle the
Adding the handler to the textboxes is easily done with a foreach loop in the form constructor:
Now the user can't leave a textbox empty. The handler returns the focus back to the textbox. To exclude a textbox from being validated simply set the
Validating event:private void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox currenttb = (TextBox)sender;
if(currenttb.Text == "")
MessageBox.Show(string.Format("Empty field {0 }",currenttb.Name.Substring(3)));
e.Cancel = true;
else
{
e.Cancel = false;
}
}Adding the handler to the textboxes is easily done with a foreach loop in the form constructor:
foreach(TextBox tb in this.Controls.OfType().Where(x => x.CausesValidation == true))
{
tb.Validating += textBox_Validating;
}Now the user can't leave a textbox empty. The handler returns the focus back to the textbox. To exclude a textbox from being validated simply set the
CausesValidation property to false.Code Snippets
private void textBox_Validating(object sender, CancelEventArgs e)
{
TextBox currenttb = (TextBox)sender;
if(currenttb.Text == "")
MessageBox.Show(string.Format("Empty field {0 }",currenttb.Name.Substring(3)));
e.Cancel = true;
else
{
e.Cancel = false;
}
}foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(x => x.CausesValidation == true))
{
tb.Validating += textBox_Validating;
}Context
StackExchange Code Review Q#54636, answer score: 10
Revisions (0)
No revisions yet.