-
Notifications
You must be signed in to change notification settings - Fork 34
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Question: How do I validate dependent fields - Multiple fields in single validation logic #48
Comments
I'm also interested in how we can do this. |
I want to know this as well! It would be handy :) |
Maybe a conditional function data class Vehicle {
val name: String,
val type: VehicleType,
val fuel: FuelType
} {
init {
validate(this) {
validate(Vehicle::fuel)
.isNotEqualTo(FuelType.DIESEL)
.when { it.type is VehicleType.TWO_WHEELER}
}
}
} |
I had the same problem. Here's the way I've solved it. data class Vehicle(
val name: String,
val type: VehicleType, // VehicleType is either TWO_WHEELER or FOUR_WHEELER
val fuel: FuelType // FuelType is either PETROL or DIESEL
)
// declare function that returns the function which returns Boolean
val bikeEngineValidation: (type: VehicleType) -> (fuel: FuelType) -> Boolean = { vehicle ->
{ fuel ->
!(vehicle == VehicleType.TWO_WHEELER && fuel == FuelType.DIESEL)
}
}
// invalid bike
val bike = Vehicle("bike", VehicleType.TWO_WHEELER, FuelType.DIESEL)
try {
validate(bike) { vehicle ->
validate(Vehicle::fuel).isValid { bikeEngineValidation(vehicle.type)(it) }
}
} catch (ex: ConstraintViolationException) {
ex.constraintViolations
.map { "got validation error -> ${it.property}: ${it.constraint.name}" }
.forEach(::println)
} Reponse: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am not able to figure out how to validate dependent fields e.g.
There should be a easy way to define a constraint such that if vehicle.type is VehicleType.TWO_WHEELER, vehicle.type cannot be FuelType.DIESEL
I have no idea how to achieve this right now.
The text was updated successfully, but these errors were encountered: