多次验证相同的输入字段是一个好习惯吗?

I am involved in a web development project using some existing PHP framework. The web app involves taking some user input data from a web form and then save the data, along with some internally generated data, into various tables in a database. As I debug the existing code (of course, the code was not designed by me), I found that the existing code is validating the same input field multiple times. The web form itself has about 10 input fields. But the tracing results show that there are about 250 hits to the StringValidator alone. I have not yet counted the hits on the other validators (such as IntegerValidators, etc.).

All the validations that I am talking about here are at the backend, and the validation rule is the same for the same input field -- that is, the code is now just using the same validation rule multiple times on the same input field. For instance, there is a field by ID "first_name" and the code is validating whether this field is a string 5 or 6 times. I am not talking about validating the same input field with several different validators (for instance, required, string, not containing exotic characters, etc.)

So, what do you think about this kind of practice of coding: good, ok, bad? Or this kind of wasting of PHP execution time is ok?

Thank you very much in advance for your opinion!

In my opinion, in terms of validating, it is okay to validate a same input multiple times. There will be some cases for that, for example:

  • The field must contain specific number of character
  • The field must not include special character (or just ascii character)
  • The field must be exists in a certain database record
  • The record of the field (that has been found) must have some privilege to do some action.

But counting of 10 fields using 250 validation, i think that is too much. You have to break up the code and find what is it doing. If it runs the same validation rule more than twice, it is bad.

Why i said twice is okay? There is when we validate the input in frontend, then do the ajax validation with rule A. Then upon submit process, we double check to validate with rule A again in the server.

There is no point in re-verifying the same thing over and over if the thing you are looking at does not change between checks. Check once and move on. Doing otherwise is bad practice and just wastes time, because if the thing you are checking doesn't change, your result won't change either.

I hope this helps!