making / yavi

Yet Another Validation for Java (A lambda based type safe validation framework)
https://yavi.ik.am
Apache License 2.0
756 stars 62 forks source link

how to create Custom Constraint Validation Error structs #364

Closed jeusdi closed 7 months ago

jeusdi commented 7 months ago

I see that all Validated or Validation objects that a Validator returns, have a ConstraintViolation as declared E type.

Validated<Reference> validate = ArgumentsValidatorBuilder.of(Reference::new)
    .builder(b -> b
        .constraint(_ReferenceArgumentsMeta.REFERENCEUNIQUEIDENTIFIER, c -> c.notNull())
        .constraint(_ReferenceArgumentsMeta.TRANSACTIONID, c -> c.notNull())
        .constraint(_ReferenceArgumentsMeta.DOCUMENTID, c -> c.notNull()))
    .build()
    .validate(referenceUniqueIdentifier, transactionId, documentId, ReferenceGroup.ofEmpty());

I mean, all validation errors of validate object are of type ConstraintViolation.

I'd like to construct custom Validation structures instead of ConstraintViolation by default. For example:

private static Validation<DomainReferenceFailure, ReferenceUniqueIdentifier> uniqueIdentifierNonNull(
        ReferenceUniqueIdentifier referenceUniqueIdentifier) {

    return Optional.ofNullable(referenceUniqueIdentifier)
            .map(Validation::<DomainReferenceFailure, ReferenceUniqueIdentifier>success)
            .orElse(Validation.failure(
                    new DomainReferenceFailure(new InvalidReferenceUniqueIdentifierError(referenceUniqueIdentifier))));
}

How could I get this using above fluent syntax approach?

Another question: Is there any way to "combine" or merge a stream of Validation<DomainReferenceFailure>? or I need to combine them one by one?

making commented 7 months ago

I don't understand what you are trying to accomplish. The code presented doesn't work?

jeusdi commented 7 months ago

Code above works.

My question is about how could I get custom Validation<MyError, T> instead of always Validation<ConstraintViolation, T> or Validated<T>...

I mean, ArgumentsValidatorBuilder.of(......).build().validate(...) always returns an Validated<T> akka Validation<ConstraintViolation, T>. I like to get Validation<MyError, T> instead of.

making commented 7 months ago

That's not the intended usage. As a general utility, I have created Validation interface in am.ik.yavi.fn package, but am.ik.yavi.core package uses the specific Validated type.