Home > Enterprise >  IHP: How to validate a field with the value from an other field
IHP: How to validate a field with the value from an other field

Time:09-17

I want to validate a field with the value from an other field in the Create/UpdateAction. I tried the following:

buildCo2Producer co2Producer =
  co2Producer
    |> fill @["commonSingleConsumptionFrom", "commonSingleConsumptionTo"]
    |> validateField #commonSingleConsumptionFrom (isGreaterThan 0)
    |> validateField #commonSingleConsumptionTo (isGreaterThan $ get #commonSingleConsumptionFrom co2Producer)

I wish #commonSingleConsumptionTo to be greater than #commonSingleConsumptionFrom, but no matter what I enter in the form, #commonSingleConsumptionFrom is always 0 in this validation.

CodePudding user response:

So my mistake was that I validated with the initial co2Producer record and not with the "filled" one that is piped through. To solve this I made a function that can take a "other field" and validate with that:

buildCo2Producer co2Producer =
  co2Producer
    |> fill @["commonSingleConsumptionFrom", "commonSingleConsumptionTo"]
    |> validateField #commonSingleConsumptionFrom (isGreaterThan 0)
    |> validateWithOtherField #commonSingleConsumptionTo isGreaterThan #commonSingleConsumptionFrom 
  where
    validateWithOtherField field validateFunction validateWithField record = validateField field (validateFunction $ get validateWithField record) record

CodePudding user response:

Here's another possible solution :) Using a lambda expression \co2Producer -> ... to capture the piped co2Producer.

buildCo2Producer co2Producer =
  co2Producer
    |> fill @["commonSingleConsumptionFrom", "commonSingleConsumptionTo"]
    |> validateField #commonSingleConsumptionFrom (isGreaterThan 0)
    |> \co2Producer -> validateField #commonSingleConsumptionTo (isGreaterThan $ get #commonSingleConsumptionFrom co2Producer) co2Producer
  • Related