Reputation: 2845
I am new in validation.
controller:
@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";
but @Email
not giving custom message and pattern also not working.Kindly solve my problem.
Thanks.
Upvotes: 0
Views: 6545
Reputation: 1709
1- Add the necessary dependencies in pom.xml file from Maven Central:
2- Add the necessary Annotations in your form bean:
@NotEmpty(message = "{email.notempty}")
@Email
private String email;
3- To read messages from message.properties, you have to define the 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- To avoid having the custom validator ignored, you have to set the validator by overriding the getValidator() method. Set validation message source to message.properties.
@Bean(name = "validator")
@Override
public LocalValidatorFactoryBean getValidator() {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource());
return bean;
}
5- in the message.properties file under src/main/resources just define a property message like:
email.notempty=This field is required.
note : If it does not work yet you can still do this.
javax.validation.constraints.Email.message=Please provide valid email id.
Upvotes: 0
Reputation: 558
You can implement like that.
@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;
}
Upvotes: 2