konform-kt / konform

Portable validations for Kotlin
https://www.konform.io
MIT License
651 stars 39 forks source link

How to achieve Password matching? #35

Closed ronjunevaldoz closed 2 years ago

cies commented 2 years ago

I hope this helps:

    val validator = Validation<SignupFormDto> {
      SignupFormDto::password required {}
      SignupFormDto::confirmPassword required {}

      val checkPasswordsMatch = Validation<SignupFormDto> {
        addConstraint("Passwords should match") {
          if (it.password == null || it.confirmPassword == null) {
            true // dont whine about non matching passwords when not filled in yet
          } else {
            it.password == it.confirmPassword
          }
        }
      }
      SignupFormDto::discountedPlanPriceUntil {
        run(checkPasswordsMatch)
      }
    }

I've not tested this, but I hope this helps you. Sorry for the late response, I've only just learned about this library.

nlochschmidt commented 2 years ago

@ronjunevaldoz did this answer your question?

Note that the snippet suffers from the issue described in #37.

Also, the addConstraint can be directly applied to the outer Validation<SignupFormDto>. This means it can be simplified to:

data class SignupFormDto(val password: String?, val confirmPassword: String?)

val validator = Validation<SignupFormDto> {
    SignupFormDto::password required {}
    SignupFormDto::confirmPassword required {}

    addConstraint("Passwords should match") {
        if (it.password == null || it.confirmPassword == null) {
            true // dont whine about non matching passwords when not filled in yet
        } else {
            it.password == it.confirmPassword
        }
    }
}

println(validator(SignupFormDto("Secret", "NoSecret")))
// Invalid(errors=[ValidationError(dataPath=, message=Passwords should match)])

println(validator(SignupFormDto("Secret", "Secret")))
// Valid(value=SignupFormDto(password=Secret, confirmPassword=Secret))
nlochschmidt commented 2 years ago

Closing because of inactivity.