As explained in this previous post, validateOrFail acts as a kind of filter if you validate a struct. Input of this filter is your request collection( a struct) or a user-defined struct. The nice thing here is: validateOrFail will only return your validated fields, and this way you get rid of all kind of unwanted other fields in your request scope which can help secure your input. At least, that’s what the docs indicate
I wouldn’t write this post if this was 100% valid, so let’s see what’s going on based on my simple use case.
How often do you want to be sure values in your newly inserted records are unique? I just counted in my current project: 28 times. That’s a lot of repetitive code if you validate this requirement each time, so it makes sense to use some kind of uniqueness validator in cbvalidation. In older releases of cbvalidation there only was a unique validator for ORM which looks like this:
So pretty easy, you don’t have to specify tablenames, fieldnames or primary keys. That’s only possible if you are using ORM entities, because they have all database information included in the entity definition. So if you want to use request collection validation you are out of luck( in a previous post I explained why this might be a good idea ).
Recently I was coding a fluent API based on this sample code which was presented at ITB 2020 by Gavin Pickin. When I was testing I discovered I could overwrite existing records when trying to insert new ones, which sounds like a huge security vulnerability. But before blaming Gavin for this let me confess I changed the code a little, just enough to create this security hole. So this exercise showed me the following:
never ever populate a model automatically from the request collection without realizing what your customers can insert.
validating your request collection before populating your model has it advantages.
Yesterday someone had an interesting use case for the cbvalidation library. I presented at ITB2020 about cbvalidation, and I’ve contributed some code so I thought it had no secrets anymore. But when trying to solve this case I discovered cbvalidation still had some hidden lines for me. When discussing this validation problem we tried to solve it with UDF validators, but -spoiler alert-finally we agreed it was not powerful enough. So time to build a CustomValidator, which is a lot easier than you might think.