dataclass
dataclass copied to clipboard
How to override the `validate` method?
The documentation suggests that custom validation must be done in the constructor:
Validating in the constructor is useful when you have validation rules spanning multiple fields.
But the problem is that these custom validation rules are not reflected in the generated validate method, resulting in a different validation if you create a new instance or if you call the validate method.
It should be preferable to perform custom validation in the validate method than in the constructor (because the validate method is called by the constructor).
So, how can we override the validate method?
That's a good point, I've been thinking about overriding validate before for the same purpose. The issue I can see is that it would take some convention to use, which I'm always a bit hesitant to add.
This is how the code is generated:
// If field has validators and is not nullable
if(data.FIELD != VALIDATOR)
setError("FIELD", Option.Some(data.FIELD));
// If field is not nullable
if(data.FIELD == null)
setError("FIELD", Option.None);
// === Insert custom code here? ===
// Done
return if(hasErrors) Some(errors) else None;
As you can see, there is some convention to learn, including being aware that the custom code will be inserted in the middle of this function. Maybe you have another idea?
Hmmm... 🤔 The data class could implement a dedicated static method, let's say customValidate(data, errors), that would be called by the validate() method if it exists. The check for its existence could use reflection or, better, be based on a dedicated interface (i.e. class Model implements DataClass implements CustomValidation).