My struct I want to bind data to is:
type Form_Eingabe struct {
Eingabe1 float64 `json:"eingabe1" form:"eingabe1" binding:"required,numeric,gt=0,max=1000000000"`
Eingabe2 float64 `json:"eingabe2" form:"eingabe2" binding:"required,numeric,gt=0,max=99"`
}
Basically everything works, but I wanted to check my application against the fact that some people may send bad info over. So basically a string
instead of a float
.
My process flow is like this:
- c.Bind()
- validate with validators
Like I said, if you send float values everything is fine, but if you for example send a string, everything misbehaves.
Here some examples:
Example 1 (Works)
INPUT:
- eingabe1 = 1000
- eingabe2 = 12.2
OUTPUT:
- eingabe1 = 1000
- eingabe2 = 12.2
Example 2 (breaks completely)
INPUT:
- eingabe1 = “some string”
- eingabe2 = 12.2
OUTPUT:
- eingabe1 = 0
- eingabe2 = 0
Example 3 (breaks partially)
INPUT:
- eingabe1 = 1000
- eingabe2 = “some string”
OUTPUT:
- eingabe1 = 1000
- eingabe2 = 0
According to this data (which I debugged and analysed) c.Bind() will stop processing any new data, as soon as the first error occurred. So if I had 5 values and the error is in the first, all data is zero, if it happens in the third, all from there is 0, but all before are set. Even if the 4th & 5th values would be valid again, they will not be set!
I don’t have a problem with the wrong values being set to 0, but I have a problem with:
- all from there (valid or not) will be set to 0 as well
- NO ERRORS are set to this input, but just one single general error is triggered.
My bind & validate section looks like this:
[...]
if err := c.Bind(&form); err != nil {
var ve validator.ValidationErrors
if errors.As(err, &ve) {
out = make([]Fehler_entry, len(ve))
for i, fe := range ve {
out[i] = Fehler_entry{fe.Field(), getErrorMsg(fe)}
F = append(F, out[i])
}
fmt.Println(F)
p = Messages{Debug: D, Fehler: F}
c.HTML(200, "main.html", p)
return
}
[...]
}
[...]
So if someone fills in a string I just get this message:
strconv.ParseFloat: parsing "some string": invalid syntax
but no info whatsoever on, which field triggered this.
If all bindings are ok, but just the validation fails I get good errors like this:
Key: 'Form_Eingabe.Eingabe1' Error:Field validation for 'Eingabe1' failed on the 'max' tag
This clearly tells me which field and why.
I added a validator “numeric”, so int and float are accepted, but as the validation happens after the binding this never runs.
Does anyone know how I can fix this, so that if a field fails to bind, I know exactly which one and also how to make this not break, but then just scip this field and set an error, hopefully very similar to the one I get from the validator itself.
I know that is much to ask for, but I have already tried for two whole days to fix that and can’t see how to do so.