Есть ли способ, которым мы можем использовать два пользовательских сообщения об ошибках с помощью специальной проверки при загрузке? - PullRequest
1 голос
/ 05 июня 2019

Я использую приведенный ниже пользовательский код проверки для проверки personName, и, похоже, он работает нормально, но проблема в том, что когда я передаю ПУСТОЙ строку, он выдает то же сообщение об ошибке, а не пустое сообщение об ошибке. Может кто-нибудь помочь мне с этим?


@Documented
@Constraint(validatedBy = {PersonNameValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@ReportAsSingleViolation
public @interface PersonName {

    /**
     * Default error message defined for the validator.
     *
     * @return message
     */
    String message() default "invalid person name";

    /**
     * Method to define groups parameters for validation.
     *
     * @return groups
     */
    Class[] groups() default {};

    /**
     * Method to load payload.
     *
     * @return payload
     */
    Class<? extends Payload>[] payload() default {};

}


public class PersonNameValidator implements ConstraintValidator<PersonName, String> {

    @Override
    public boolean isValid(String name, ConstraintValidatorContext context) {
        if (name.length() == 0) {
            throw new IllegalArgumentException("must not be Empty");
        } else if (!name.matches("(?=^(?!\\s*$).+)(^[^±!@£$%^&*_+§€#¢§¶•«\\\\/<>?:;|=]{1,256}$)")) {
            throw new IllegalArgumentException("name should start with uppercase.");
        }
        return true;
    }
}


@Data
public class NameDto {

    @NotNull
    @PersonName
    private String family1Name;

    @PersonName
    private String family2Name;

    @NotNull
    @PersonName
    private String givenName;

    @PersonName
    private String middleName;
}



Получение исключения NullPointerException

1 Ответ

0 голосов
/ 05 июня 2019
  @Name
  @NotEmpty(message = "name cannot be empty")
  String name;

должно работать

, но если вы хотите присоединить ограничение, вы должны использовать пользовательский ConstraintValidator добавить, предоставьте этот валидатор через @Constraint(validatedBy = {YourCustomValidator.class} см. Пример ниже


полный пример

используемая зависимость spring-boot-starter-validation (не требуется, если вы используете spring-boot-starter-web )

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
   </dependency>

application.properties

upper.name=dirk

application

package stackoverflow.demo;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

@SpringBootApplication
public class SoCustomValidationApplication {

    public static void main(String[] args) {
        SpringApplication.run(SoCustomValidationApplication.class, args);
    }

}

@Component
class ConfigurationLoader{
  final MyCustomValidatedProperties config;

  ConfigurationLoader(MyCustomValidatedProperties config){
    this.config = config;
  }

  @EventListener()
  void showName() {
    System.err.println("name is: " + config.getName());
  }
}

@org.springframework.context.annotation.Configuration
@Validated
@ConfigurationProperties(prefix = "upper")
class MyCustomValidatedProperties {

  @Uppercase
  @NotEmpty(message = "name cannot be empty")
  String name;

  public String getName() {
        return name;
    }

  public void setName(String name) {
        this.name = name;
    }
}

@Constraint(validatedBy = {ValidNameValidator.class})
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
@interface Uppercase {
  String message() default "name should start with uppercase";

  Class[] groups() default {};

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

class ValidNameValidator implements ConstraintValidator<Uppercase, String> {

  @Override
  public boolean isValid(String name, ConstraintValidatorContext context) {
    if (null == name || 0 == name.length() ) {
        throw new IllegalArgumentException("name cannot be empty.");
    } else if(!name.matches("^([A-Z][a-z]+)")) {
      throw new IllegalArgumentException("name should start with uppercase.");
    }
    return true;
  }
}

Приложение не удалось запустить

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'upper' to stackoverflow.demo.MyCustomValidatedProperties$$EnhancerBySpringCGLIB$$d0094cdb failed:

    Property: upper.name
    Value: dirk
    Origin: class path resource [application.properties]:1:12
    Reason: name should start with uppercase

и если вы оставите поле upper.name пустым

upper.name=

Приложение не удалось запустить

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'upper' to stackoverflow.demo.MyCustomValidatedProperties$$EnhancerBySpringCGLIB$$29925f50 failed:

    Property: upper.name
    Value: 
    Origin: class path resource [application.properties]:1:12
    Reason: name cannot be empty

    Property: upper.name
    Value: 
    Origin: class path resource [application.properties]:1:12
    Reason: name should start with uppercase
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...