开发者

Validating form input and running a function only if it passes

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 neste开发者_如何学Cd 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜