Skip to content
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

Open
ranedk opened this issue Jul 21, 2020 · 4 comments

Comments

@ranedk
Copy link

ranedk commented Jul 21, 2020

I am not able to figure out how to validate dependent fields e.g.

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
}

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.

@trickyBytes
Copy link

I'm also interested in how we can do this.

@Welcius
Copy link

Welcius commented Nov 16, 2020

I want to know this as well! It would be handy :)

@jusexton
Copy link

jusexton commented Nov 28, 2020

Maybe a conditional function when can be added to the end of constraint statements. The updated API might look like the below:

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}
        }
    }
}

@kkojot
Copy link

kkojot commented Feb 10, 2022

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: got validation error -> fuel: Valid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

5 participants