Code Monkey home page Code Monkey logo

Comments (8)

making avatar making commented on August 29, 2024

@enricosecondulfo Can you provide a sample code?

from yavi.

enricosecondulfo avatar enricosecondulfo commented on August 29, 2024

I'm sorry to answer that now. I'll give you a very common example of a custom validation that I often use:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotExistsValidator.class)
public @interface NotExists {

    String message() default "already exists";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String parameter() default "";

    Class<?> clazz() default String.class;
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class NotExistsValidator implements ConstraintValidator<NotExists, Object> {

    @Autowired
    private MongoOperations mongoOperations;

    private NotExists constraintAnnotation;

    @Override
    public void initialize(NotExists constraintAnnotation) {
        this.constraintAnnotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Criteria criteria = Criteria.where(this.constraintAnnotation.parameter()).is(value);
        return !this.mongoOperations.exists(new Query(criteria), this.constraintAnnotation.clazz());
    }
}

Thank your so much

from yavi.

enricosecondulfo avatar enricosecondulfo commented on August 29, 2024

@making Can i archive this? Thank you

from yavi.

making avatar making commented on August 29, 2024

I think you can do if you define the validator in the constructor of the controller or service class after MongoOpearation injected

from yavi.

enricosecondulfo avatar enricosecondulfo commented on August 29, 2024

@making Could you give me a practical example of how to create such a custom validation, please?

from yavi.

making avatar making commented on August 29, 2024

@enricosecondulfo

public class Foo {

    private final String id;

    public Foo(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.Validator;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.function.Function;

@RestController
public class FooController {

    private final FooService fooService;

    private final Validator<Foo> validator;

    public FooController(FooService fooService) {
        this.fooService = fooService;
        this.validator = Validator.<Foo>builder()
            .constraintOnObject(Function.identity(), "foo.id", c -> c.predicate(new FooCustomConstraint(this.fooService)))
            .build();
    }

    @PostMapping("/{id}")
    public Object post(@PathVariable("id") Foo foo) {
        return this.validator.validateToEither(foo)
            .fold(ConstraintViolations::details, x -> "OK");
    }
}
import am.ik.yavi.core.CustomConstraint;

public class FooCustomConstraint implements CustomConstraint<Foo> {

    private final FooService fooService;

    public FooCustomConstraint(FooService fooService) {
        this.fooService = fooService;
    }

    @Override
    public String messageKey() {
        return "foo.unique";
    }

    @Override
    public String defaultMessageFormat() {
        return "{0} must be unique.";
    }

    @Override
    public boolean test(Foo foo) {
        return !this.fooService.isExists(foo);
    }
}
import org.springframework.stereotype.Service;

@Service
public class FooService {

    public boolean isExists(Foo foo) {
        return "1".equals(foo.getId());
    }
}

from yavi.

enricosecondulfo avatar enricosecondulfo commented on August 29, 2024

@making thank you a lot, the example is very clear and exhaustive

from yavi.

making avatar making commented on August 29, 2024

You're welcome

from yavi.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.