有什么办法可以通过spring-boot自定义验证来使用两个自定义错误消息?

时间:2019-06-05 16:01:58

标签: spring-boot

我正在使用下面的自定义验证代码来验证personName,它似乎运行良好,但是问题是当传递EMPTY字符串时,它给出的是相同的错误消息,而不是空的错误消息。有人可以帮我吗?


@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 :(得分:0)

  @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

应用

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