简体   繁体   中英

HV000030: No validator could be found for constraint 'javax.validation.constraints.Size' validating type 'java.util.Optional<java.lang.String>'

Hello guys I'm trying to get the validation on the YAML

- name: campo
        in: query
        schema:
          type: string
          pattern: '[S|N]' #pattern
          maxLength: 1

Using maven spring boot and delegate. On the RestController I added annotation @Validated and I'm able to validate required=true fields, but if fields are not require, as per architecture design, parameter will be Optional<String> . For this java.util.Optional , trying to test and validate, throw title error:

{
  "timestamp": "2020-10-21T07:50:18.651+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "HV000030: No validator could be found for constraint 'javax.validation.constraints.Size' validating type 'java.util.Optional<java.lang.String>'. Check configuration for 'metodo.campo'",
  "path": "/%7BbasePath%7D/microservicio/metodo"
}

¿Anyway to solve this issue to have this Optional<String> validation proccessed correctly? We don't want to write all code for validation on Java if can be done on YAML + validation (@Valid and @Validated).

EDIT: The validation @Size and others is generated from YAML with open api version 3.0.3

You should write: Optional<@Size String> (which would check the size of the String inside the optional) instead of @Size Optional<String> (which is supposed to check the size of the optional, which is meaningless).

See Hibernate Validator: With java.util.Optional :



package org.hibernate.validator.referenceguide.chapter02.containerelement.optional;

public class Car {

    private Optional<@MinTowingCapacity(1000) Integer> towingCapacity = Optional.empty();

    //...

}

The newer version Jakarta Bean Validation 2.0 newly supports Optional validation as of August 2019. You can find this information out at their changelog summary 2. What's new :

Support for java.util.Optional

The only certified implementation, is Hibernate Validator 6.0.17.Final as of September this year.

Consider an upgrade, ohterwise you would have to omit the size validation and perform it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM