javax.validation.constraints @Email是否不返回自定义消息和正则表达式?

时间:2018-08-24 10:02:53

标签: java regex hibernate validation spring-boot

我是验证的新手。

控制器:

@Validated
@RestController
public class AccountController
{
    @PostMapping( value = "/account/location" )
    public ResponseEntity<LocationAccountVO> createLocationAccount( @RequestHeader 
HttpHeaders headers,@Valid @RequestBody LocationAccountVO locationAccountVO ) throws 
NumberParseException
    {
        return ResponseEntity.status(HttpStatus.CREATED).body( 
accountService.createLocationAccount( locationAccountVO ) );
    }
}

LoacationVo.java:

@Data
@JsonInclude( JsonInclude.Include.NON_NULL )
public class LocationAccountVO
{
private UUID locationId;
    @NotNull(message = "Email is mandatory.")
    @Email( regexp = ValidationConstant.EMAIL, message = "Email be valid")
    private String email;
}

public static final String EMAIL = "\\\\b[A-Z]+@[A-Z0-9.-]+\\\\.[A-Z]{2,4}\\\\b";

但是@Email没有提供自定义消息和模式也无法正常工作。请解决我的问题。

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以这样实现。

@Data
@JsonInclude( JsonInclude.Include.NON_NULL )
public class LocationAccountVO
{
private UUID locationId;
    @NotEmpty(message = "Email is mandatory.")
    @Pattern(regexp = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", message = "Email be valid")
    private String email;
}

答案 1 :(得分:0)

1-在enter image description here的pom.xml文件中添加必要的依赖项:

  • spring-boot-starter-web
  • spring-boot-starter-validation

2-在表单bean中添加必要的注释:

@NotEmpty(message = "{email.notempty}")
@Email
private String email;

3-要从message.properties中读取消息,必须定义MessageSource Bean

@Bean
public ResourceBundleMessageSource messageSource() {
    final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    messageSource.setUseCodeAsDefaultMessage(Boolean.parseBoolean("true");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

4-为了避免忽略自定义验证器,您必须通过重写getValidator()方法来设置验证器。将验证消息源设置为message.properties。

@Bean(name = "validator")
@Override
public LocalValidatorFactoryBean getValidator() {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}

5-在src / main / resources下的message.properties文件中 只需定义一个属性消息,如:

email.notempty=This field is required.

注意:如果仍然无法运行,您仍然可以这样做。

javax.validation.constraints.Email.message=Please provide valid email id.