konform icon indicating copy to clipboard operation
konform copied to clipboard

How to put a hint on an empty required block?

Open cies opened this issue 4 years ago • 4 comments

From the README it is not clear how I put a hint on an empty required block.

    val validator = Validation<DealFormDto> {
      DealFormDto::closedBy required {}
    }

I get the "is required" default message when closedBy is not present. But how to set my own message?

This does not work:

    val validator = Validation<DealFormDto> {
      DealFormDto::closedBy required { hint "Closed by is missing" }
    }

cies avatar Apr 14 '22 10:04 cies

We now use this custom validation this in order to specify the hint on a required property:

fun <T : Any?> ValidationBuilder<T>.required() = addConstraint("is required") {
  if (it == null) {
    false
  } else {
    when (it) {
      is String -> it.isNotBlank()
      is Collection<*> -> it.isNotEmpty()
      else -> true
    }
  }
}

Which we use like this:

      FormDto::estimatedAnnualSales { required() hint "Estimated sales is required" } // Note we control the error message
      FormDto::estimatedAnnualSales ifPresent { minimum(0) hint "Estimated sales cannot be negative" }

Where before we'd do something like this:

      FormDto::estimatedAnnualSales required { minimum(0) hint "Estimated sales cannot be negative" }
      // Note we have no control over the error given when `estimatedAnnualSales` is omitted, it will always be "is required"

cies avatar Apr 19 '22 08:04 cies

And we now use this one as well:

/** Convenience method, same as `required()` but takes a name. */
fun <T : Any?> ValidationBuilder<T>.requiredAs(name: String) = addConstraint("{0} is required", name) {
  if (it == null) {
    false
  } else {
    when (it) {
      is String -> it.isNotBlank()
      is Collection<*> -> it.isNotEmpty()
      else -> true
    }
  }
}

cies avatar Apr 19 '22 08:04 cies

Awesome that you found a solution that works using the existing extension points 👏

Which we use like this:

    FormDto::estimatedAnnualSales { required() hint "Estimated sales is required" } // Note we control the error message
    FormDto::estimatedAnnualSales ifPresent { minimum(0) hint "Estimated sales cannot be negative" }

I agree, that doesn't look very good to me

So additionally to the one design option you proposed there are at least two other design options that I think are interesting:

Option 1: Your proposed option

DealFormDto::closedBy required { hint "Closed by is missing" }

Option 2: Using optional hint parameter on required

DealFormDto::closedBy required(hint = "Closed by is missing") { }

Option 3: Using infix after the required block

DealFormDto::closedBy required { } hint "Closed by is missing"

I think Option 3 is most in line with the existing idioms and, might possibly be easier to implement as well.

nlochschmidt avatar May 03 '22 19:05 nlochschmidt