I recently came up to an issue related to validation. Typically, I am building a REST api that allow users to create their account including avatars. All of the information should be submitted when user clicks to Register button. So, my server will then receive a request that includes some fields like name (string), birthday (datetime), ... and avatar (multipart file). So, the question is how to validate the received file is a truly image and has an allowed size and simultaneously validate that the others (email, password) are also valid.
For the case that all fields is text, we can easily validate them using the combination of annotations like this
Controller
#PostMapping(path = "")
public ResponseEntity<?> createNewAccount(#RequestBody #Valid RegisterRequest registerRequest) {
Long resourceId = service.createNewCoderAccount(registerRequest);
return ResponseEntity.created(location(resourceId)).build();
}
Request DTO
#ConfirmedPassword
public class RegisterRequest extends BaseRequest implements ShouldConfirmPassword {
#NotBlank(message = "Field 'email' is required but not be given")
#Email
#Unique(message = "Email has been already in use", service = UserValidatorService.class, column = "email")
private String email;
#NotBlank(message = "Field 'password' is required but not be given")
#Size(min = 6, message = "Password should contain at least 6 characters")
private String password;
#NotBlank(message = "Field 'confirmPassword' is required but not be given")
private String confirmPassword;
#NotBlank(message = "Field 'firstName' is required but not be given")
private String firstName;
#NotBlank(message = "Field 'lastName' is required but not be given")
private String lastName;
}
Or in case that the request containing only file(s), we can absolutely do like this
Controller
#PostMapping(path = "/{id}")
public ResponseEntity<?> editChallengeMetadata(
#ModelAttribute ChallengeMetadataRequest request,
BindingResult bindingResult,
#PathVariable("id") Long id,
#CurrentUser User user
) throws BindException {
challengeMetadataRequestValidator.validate(request, bindingResult);
if (bindingResult.hasErrors()) {
throw new BindException(bindingResult);
}
Long challengeId = service.updateChallengeMetadata(id, request, user);
return ResponseEntity.ok(RestResponse.build(challengeId, HttpStatus.OK));
}
Validator
public class ChallengeMetadataRequestValidator implements Validator {
#Override
public boolean supports(#NonNull Class<?> aClass) {
return ChallengeMetadataRequest.class.isAssignableFrom(aClass);
}
#Override
public void validate(#NonNull Object o, #NonNull Errors errors) {
ChallengeMetadataRequest request = (ChallengeMetadataRequest) o;
if (request.getBanner() != null && !request.getBanner().isEmpty()) {
if (!List.of("image/jpeg", "image/png").contains(request.getBanner().getContentType())) {
errors.rejectValue("banner", "challenge.mime-type.not-supported", new String[]{request.getBanner().getContentType()}, "Mime-type is not supported");
}
}
}
}
As you seen above, if I wrap all data (including avatar) in a DTO class, I definitely write its own validator. But what will happen if then I have to write manually hundreds validators like that.
So, do anyone have any idea about it, typically, make the multipart/form-data request becomes simalar with application/json request ?
Thanks and regards,
Related
I have a spring boot project in which I'm facing a data validation issue while doing a post request.
Problem
While doing a post request I'm mapping the request body to a POJO which does not have any javax validations in itself, but the class has fields of another two POJOs which have data validations in them. How can I trigger data validations in the inner POJOs programmatically and throw relevant exceptions if required. I'm using Spring boot v2.5.2.
In the post request I have:
#PostMapping("/signup")
public ResponseEntity<String> addNewUser(#RequestBody #Valid NewUserDetailsPojo newUserDetailsPojo) {
log.debug("Adding new User: {}", newUserDetailsPojo);
Integer userId = userService.addNewUser(newUserDetailsPojo);
if (userId == null) {
return ResponseEntity.badRequest().build();
} else {
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(userId).toUri();
return ResponseEntity.created(location).build();
}
}
Where NewUserDetailsPojo is a simple POJO class having structure:
public class NewUserDetailsPojo {
private BasicDetailsPojo basicDetailsPojo;
private DoctorPojo doctorPojo;
// constructor
public NewUserDetailsPojo(BasicDetailsPojo basicDetailsPojo, DoctorPojo doctorPojo) {
/** before mapping the incoming data to the fields, I want to validate the data
* with my predefined javax.validations constraints declared in the respective
* classes
*/
this.basicDetailsPojo = basicDetailsPojo;
this.doctorPojo = doctorPojo;
}
}
So, as I mentioned earlier, NewUserDetailsPojo does not have any data validations in itself, but its two fields which are of the class
BasicDetailsPojo
DoctorPojo
have data validations in them. I want to invoke javax validations in the constructor of NewUserDetailsPojo and throw suitable exceptions if nessecery.
I'm giving the structures of BasicDetailsPojo and DoctorPojo below:
public class BasicDetailsPojo {
#Size(min = 5, message = "Name should be at least 5 characters long")
private String name;
#Email
private String email;
#Size(min = 10, message = "Contact number must be of 10 digits")
private String contactNo;
private String role;
#NotNull
#Size(min = 8, message = "Password must be 8 characters long")
private String password;
}
This is the structure of DoctorPojo:
public class DoctorPojo extends BasicDetailsPojo {
#NotNull
private String regNo;
#NotNull
private String degree;
#NotNull
private String specialization;
private String experience;
}
I think your problem will be fixed by putting #Valid annotation in the NewUserDetailsPojo class over the basicDetailsPojo and doctorPojo atributes
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=5.3#section-object-graph-validation
I am creating a new endpoint in this API, which accepts a request containing either a username or a 5 or 9-digit phone number. I need to add validations to validate the request to contain either a username OR phone number; if both are provided then return a validation error. Here is the current code I have.
#GetMapping("/users")
#Operation(summary = "API to return users based on username or phone number")
public ResponseEntity<List<UserResponseObject>> usersByNameOrNumber(
#Valid #RequestParam(name = "phone-number", required = false) #Pattern(regexp = "^(\\d{5}|\\d{9})$") String userPhoneNumber,
#Valid #PathVariable(name = "user-name", required = false) #Pattern(regexp = "^[a-zA-Z ]*$") String userName) {
try {
...
} catch (Exception e) {
...
}
}
How can I modify this block to meet the requirements? Currently, both fields are tagged as not required and there is no validation in place. I'd like it require ONLY one of these fields to be not null.
Try use optional, i dont know how solution you need.
#GetMapping("/users")
#Operation(summary = "API to return users based on username or phone number")
public ResponseEntity<List<UserResponseObject>> usersByNameOrNumber(
#Valid #RequestParam(value = "phoneNumber", required = false) #Pattern(regexp = "^(\\d{5}|\\d{9})$") Optional<String> phoneNumber,
#Valid #RequestParam(value = "userName", required = false) #Pattern(regexp = "^[a-zA-Z ]*$") Optional<String> userName) {
try {
if(phoneNumber.isPresent()){}
if(userName.isPresent()){}
} catch (Exception e) {
}
}
But i'm not sure the #Pattern and Optional will be work good, but probably yes.
Maybe is help, if i good understend your problem.
I am learning about spring rest api and wrote a following method to save the data into the database.
#GetMapping(path="/add") // Map ONLY GET Requests
public #ResponseBody String addNewUser (#RequestParam String name
, #RequestParam String email) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
User n = new User();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "Saved";
}
now i want to write the put query which can take user id and then update the name or email. Also, I need to check that username and email should not be null and also email is in valid format.
How can i construct my method using #putmapping to perform my task.
The basic validations should be done in the mapping class only.
You can refer below example:
Suppose your mapping class and request method will be like:
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.constraints.Email;
public class User {
#NotNull(message = "Name cannot be null")
private String name;
#Size(min = 10, max = 200, message
= "About Me must be between 10 and 200 characters")
private String aboutMe;
#Min(value = 18, message = "Age should not be less than 18")
#Max(value = 150, message = "Age should not be greater than 150")
private int age;
#Email(message = "Email should be valid")
#NotNull
private String email;
// setters and getters
}
#PutMapping(path="/update")
public ResponseEntity<UserResponse> updateUser(#Valid #RequestBody User user) {
return userRepository.save(user);
}
You could do it how you are suggesting, but I'd just pass the whole object to be updated:
#PutMapping(path="/update")
public #ResponseBody String updateUser(#RequestBody User user) {
userRepository.save(user);
return "Updated"; }
As for null-checking fields and validating email, you could have a validateUserFields function that takes a User object and returns a boolean so you can:
if(validateUserFields(user))
userRepository.save(user)
I'm (new in spring development) creating REST API for my application, CRUD operations are implemented successfully but now I want to implement server side validation. I've also read that there are several ways through which validation could be implemented.
Using given annotations -> #notempty, #email, etc...
Using custom validation -> extending validators
I want to implement both of them in my application, With reference to that,
is it good approach to follow?
OR
Is there any other ways through which validation can be implemented?
Controller
#RestController
public class EmployeeController {
#Autowired
DataServices dataServices;
#Autowired
EmployeeValidator employeeValidator;
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(employeeValidator);
}
#RequestMapping(value = "/employee/", method = RequestMethod.POST)
public ResponseEntity<Object> createUser(
#Valid #RequestBody Employee employee,
UriComponentsBuilder ucBuilder) throws Exception,
DataIntegrityViolationException {
if (dataServices.addEmployee(employee) == 0) {
Error error = new Error(1, "Data integrity violation",
"Email id is already exists.");
return new ResponseEntity<Object>(error, HttpStatus.CONFLICT);
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/employee/{id}")
.buildAndExpand(employee.getId()).toUri());
Status status = new Status(1, "Employee has been added successfully.");
return new ResponseEntity<Object>(status, headers, HttpStatus.CREATED);
}
}
Error Handler
#ControllerAdvice
public class RestErrorHandler {
private static final Logger logger = Logger
.getLogger(RestErrorHandler.class);
private MessageSource messageSource;
#Autowired
public RestErrorHandler(MessageSource messageSource) {
this.messageSource = messageSource;
}
#ExceptionHandler(MethodArgumentNotValidException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ResponseBody
public ValidationErrorDTO processValidationError(
MethodArgumentNotValidException ex) {
logger.debug("Handling form validation error");
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
return processFieldErrors(fieldErrors);
}
private ValidationErrorDTO processFieldErrors(List<FieldError> fieldErrors) {
ValidationErrorDTO dto = new ValidationErrorDTO();
for (FieldError fieldError : fieldErrors) {
String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError);
dto.addFieldError(fieldError.getField(), localizedErrorMessage,
fieldError.getDefaultMessage());
}
return dto;
}
private String resolveLocalizedErrorMessage(FieldError fieldError) {
Locale currentLocale = LocaleContextHolder.getLocale();
String localizedErrorMessage = messageSource.getMessage(fieldError,
currentLocale);
// If a message was not found, return the most accurate field error code
// instead.
// You can remove this check if you prefer to get the default error
// message.
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0];
}
return localizedErrorMessage;
}
}
Validator
#Component
public class EmployeeValidator implements Validator {
public boolean supports(Class clazz) {
return Employee.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", errors
.getFieldError().getCode(), "First name is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", errors
.getFieldError().getCode(),
"Last name is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", errors
.getFieldError().getCode(),
"Email is required.");
}
}
Model
#Entity
#Table(name = "employee")
#JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "id")
private long id;
// #NotEmpty(message = "Please enter first name")
#Column(name = "first_name")
private String firstName;
// #NotEmpty(message = "Please enter last name")
#Column(name = "last_name")
private String lastName;
// #NotEmpty(message = "Please enter email address")
#Email(message = "Please enter valid email address")
#Column(name = "email", unique = true)
private String email;
#NotEmpty(message = "Please enter mobile number")
#Size(min = 10, message = "Please enter valid mobile number")
#Column(name = "phone")
private String phone;
//Getter and Setter
}
In your aproach you are using Server side validations but only in the controller layer. Have you tryied to use Bussines layer validations, like Hibernate Validation API http://hibernate.org/validator/
I've used it in a recent project and form me it's a great way to keep data consistent. Some tweaks and utils were needed to make it work as we wanted but it was not too difficult. For example, this validations, by default, are only checked just after persisting a Object in database, but in our controller we needed to make this validations earlier, so you we had to implement a way to call validation mechanism that relies on hibernate validation mechanism. Or, as another example, we had to develop a similar system on a web service to return errors when incoming data was not valid.
One way to use validations when needed is to implement it on all your bussines objects. They can inherit for a class like this:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
public abstract class BusinessObject implements Serializable, IObjectWithReport, IBusinessObject {
private static Log log = LogFactory.getLog(BusinessObject.class.getName());
private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
#JsonIgnore
private Set<ConstraintViolation<BusinessObject>> errors;
/* Validation methods */
public final boolean valid() {
preValidate();
errors = new HashSet<ConstraintViolation<BusinessObject>>();
errors = validator.validate(this);
postValidate();
return errors.isEmpty();
}
/**
* Method to be overwriten in subclases so any BO can make some arrangement before checking valid
*/
protected void preValidate() {
log.trace("Generic prevalidate of " + this.getClass().getName());
}
/**
* Method to be overwriten in subclases so any BO can make some arrangement once validation has been made
*/
protected void postValidate() {
log.trace("Generic postValidate of " + this.getClass().getName());
}
public Set<ConstraintViolation<BusinessObject>> getErrors() {
return errors;
}
public boolean hasErrors() {
return errors != null && !errors.isEmpty();
}
}
Note that i use standard javax.validation.Validation API (check references here JPA 2.0 : what is javax.validation.* package?). But the implementation i use is the one from Hibernate.
Pros:
Validations are placed in one single layer, not spread along various layers. So they are easier to maintain.
Better model consistency because of that data is always validated in the same way, independently of how it was generated (user input, web service, pulled from other systems, etc).
Cons:
You need to develop some utils so you can use Model Validations in other layers, but it's not very dificult.
May be overkill if you have a simple project, whithout complexities like many info sources (user input, webservices input, rest services, other database systemas, etc) or interactions.
I'm trying to validate my form against constraints set on my bean. Spring-MVC version i am using is 3.2.4. The problem is that default Spring validator does not validate all constraints; only the ones that are of the same type.
I have the following controller code:
#Controller
#SessionAttributes()
public class FormSubmitController {
#RequestMapping(value = "/saveForm", method = RequestMethod.POST)
#ResponseBody
public ModelMap saveForm(#Valid #RequestBody Form form, HttpSession session) {
session.setAttribute("form", form);
ModelMap map = new ModelMap();
map.addAttribute("hasErrors", false);
return map;
}
}
and the following bean:
public class Form implements IForm, Serializable {
#NotNull(message = "Category should not be empty")
protected String category;
#NotNull(message = "Sub-Category should not be empty")
protected String subCategory;
#Size(min=0, message="Firstname should not be empty")
protected String firstName;
#Size(min=0, message="Lastname should not be empty")
protected String lastName;
#Pattern(regexp="^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d$", message="Date of birth should be in dd-mm-jjjj format")
protected String dateOfBirth;
//getters and setters
}
The handler for MethodArgumentNotValidException looks like this:
#ControllerAdvice
public class FormExceptionController {
#ExceptionHandler(MethodArgumentNotValidException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ResponseBody
public ModelMap handleMethodArgumentNotValidException(MethodArgumentNotValidException error) {
List<FieldError> errors = error.getBindingResult().getFieldErrors();
ModelMap map = new ModelMap();
ModelMap errorMap = new ModelMap();
map.addAttribute("hasErrors", true);
for (FieldError fieldError : errors) {
errorMap.addAttribute(fieldError.getField(), fieldError.getDefaultMessage());
}
map.addAttribute("bindingErrors", errorMap);
return map;
}
}
So, an empty form results in the first two error messages.
The firts two properties of the form filled results in the third and fourth error messages.
Only when i use the same contraint type (i.e. NotNull) for all properties on my bean it will return all error messages.
What can be wrong here?
Nothing is wrong the validator for #Size and #Pattern by default accept null as valid. So you actually need both annotations (#NotNull and #Pattern/#Size). These annotations only trigger validation of values which are non-null, these validations don't imply that null values are invalid that is where the #NotNull is for.
This is assuming you are using hibernate-vaildator (as that is the out-of-the-box supported validator).