views:

12

answers:

2

In my .NET porject, I have to run a lot of validation on 4/5 fields. This validation checks if certain fields have errors, for example: the name field is not allowed to have numbers or symbols. If all these checks are passed, I need to execute a SQL query to pull some data out of the database.

I could have it with a lot of nested IFs, and run the function at the end once it passes them all, but this will translate into about 12 nested IFs, and it seems a really bulky way to do it. I have also thought about setting a boolean value after every check, and if the value is 1 then don't run the function, else do. But of course this gets overwritten by other checks that pass.

Can anyone provide some insight? Thanks.

A: 

This might call for early exit, i.e. return as soon as a validation fails:

If Not IsValidNameField(name) Then Return
If Not IsValidDateFiled(date) Then Return
…

If you see yourself doing this in a lot of places consider if there might be an earlier point at which to validate the fields, i.e. perhaps by providing validation in appropriate property setters, and then always manipulating the field values via the properties instead of directly.

This might be more work at first but can save a lot of work in the long run. As a rule of thumb, prevent fields from ever containing invalid values. This is much cleaner and easier to maintain and debug.

Konrad Rudolph
Thanks for the idea, I can check in the keyup event or change event if it contains an invalid value. Would save a lot of hassle. :)
Matt
@Matt: No, do **not** use the `KeyUp` event for that! Instead, always use the `Validating` event for that because that’s what it’s there for. Using `KeyUp` or similar events is really, really annoying for the user (plus, it doesn’t work well).
Konrad Rudolph
A: 

You're on the right lines with your idea of a boolean variable; default it to True, then run through each validation check separately and let every one set it to False if the check fails. Then afterwards, if it still equals True, you can carry on with your SQL query.

vincebowdren
This is what I did originally, the thing is, if the first validation check comes back as False and the second one comes back as True, the query will execute even though it didn't pass one of the checks, because it got overwritten on the next check.
Matt
A check function shouldn't change the state of the variable if the check is passed; only if it fails. That way, if all of the checks pass then you'll have it equal True, but if any of them have failed it will be set to False.
vincebowdren