Conditional validation of fields in a class

C

Casper

Hi
I would like to perform some conditional validation on fields in a class and
am not sure of the best way to do this.
These fields can be mandatory or optional depending on whether other fields
are set.

Here is the method which has an input parameter of type CQuery (a class):

response = ProcessQuery(CQuery)

I would like to validate this parameter and check that all required fields
are set correctly.

Here are the fields :

Tenancy - this can be either Freehold or Leasehold
LengthOfLease - req' if Tenancy is Leasehold..
Landlord - req'd if Tenancy is Leasehold
PropertyValue - req'd if Tenancy is freehold.

The value for Tenancy, dictates which other field are mandatory or optional.

Is there a good way to do this without resorting to nested If else, If else,
if else etc.. ?
I have other classes which are more complex and these would require some
complex validation rules...and have many fields..

I have thought about serialising the class to XML at runtime and then
perhaps validating the XML against a schema, but am not sure if this is the
best way.
I have also considered using reflection, but then would still require some
way to apply the validation rules.

thanks in advance!
 
K

Kerem Gümrükcü

Hi Casper,

why dont you do something like this?
You need a button and a listview to
run that code. Then you walk the objects
properties and check whether they are
valid or not. This is just a simple example,
you are welcome to extend:

private void button1_Click(object sender, EventArgs e)
{
string propName = string.Empty;
object propValue = null;

System.Diagnostics.Process process =
System.Diagnostics.Process.GetCurrentProcess();

this.listView1.Items.Clear();

foreach (System.Reflection.PropertyInfo pi in
process.GetType().GetProperties())
{
propName = pi.Name;

ListViewItem lviPropData =
this.listView1.Items.Add(propName);

try
{
propValue = pi.GetValue(process, null);

if (propValue == null)
{
lviPropData.SubItems.Add("null");
}
else
{
lviPropData.SubItems.Add(propValue.ToString());
}
}
catch (Exception err)
{
lviPropData.SubItems.Add("Error: " + err.Message);
}
}
}


you can also do:

foreach (System.Reflection.FieldInfo fi in
process.GetType().GetFields())
{ }

or:

foreach (System.Reflection.MemberInfo mi in
process.GetType().GetMembers())
{ }


Its u to you! So you can check whether the members a set/valid/!null or
whatever
you like,...


Regards

Kerem
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top