HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is this validation sufficient to ensure that the vals are not empty?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thistheareemptyvalidationensurethatvalsnotsufficient

Problem

I'm working on a small winforms app, the goal of which is to capture data and write to xml. I'm still a child where programming is concerned so could you guys please take a look and suggest changes as I'm pretty sure that this is not a good approach.
I'm using a masked-textbox for the invoice number which should only contain numbers. I'm trying not to use a numupdown for obvious reasons.

InputVars is a public class with empty string properties (string value {get;set;})

```
private bool TestVal(string testedVal)
{
if (!String.IsNullOrEmpty(testedVal))
{
return true;
}
else
{
return false;
}
}

private InputVars SetSemVars()
{
InputVars inVars = new InputVars();
if (TestVal(txtCapt.Text))
{
inVars.captured = txtCapt.Text;
}
else
{
MessageBox.Show("Please insert your name here");
txtCapt.Focus();
}
if (TestVal(mtxtInvoiceNumber.Text))
{
inVars.invoice = mtxtInvoiceNumber.Text;
}
else
{
MessageBox.Show("Please insert the invoice number here");
mtxtInvoiceNumber.Focus();
}
if(TestVal(cmbNetwork.SelectedIndex.ToString()))
{
inVars.network = cmbNetwork.SelectedIndex.ToString();
}
else
{
MessageBox.Show("Please select the network ");
cmbNetwork.Focus();
}
if(TestVal(cmbRegion.SelectedIndex.ToString()))
{
inVars.region = cmbRegion.SelectedIndex.ToString();
}
else
{
MessageBox.Show("Please select your office code here");
cmbRegion.Focus();
}
if(TestVal(cmbSupplier.SelectedIndex.ToString()))
{
inVars.supplier = cmbRegion.SelectedIndex.ToString();
}
else
{
MessageBox.Show("Please selec

Solution


  • Don't use String.IsNullOrEmpty to validate required values.



-
You can create a method

private bool IsEmpty(string value, string errorMessage, Control controlToValidate)
{
    if ((value ?? string.Empty).Trim().Length == 0)
    {
        MessageBox.Show(errorMessage);
        controlToValidate.Focus();
        return true;
    }
    else
    {
        return false;
    }
}


instead of TestVal.

  • Consider using Validating event for validating your controls and the Tag property to associate error messages with the controls.



  • Consider using ErrorProviders.

Code Snippets

private bool IsEmpty(string value, string errorMessage, Control controlToValidate)
{
    if ((value ?? string.Empty).Trim().Length == 0)
    {
        MessageBox.Show(errorMessage);
        controlToValidate.Focus();
        return true;
    }
    else
    {
        return false;
    }
}

Context

StackExchange Code Review Q#4101, answer score: 3

Revisions (0)

No revisions yet.