Nilucshan Siva
Nilucshan Siva

Reputation: 453

Request body validation in Spring boot application Fails

I want my REST API to throw an exception whenever there exist and parameter type mismatch. Following is my request object.

public class MyReqDto {
    @NotNull
    @Pattern(regexp = "[^a-zA-Z0-9]", message = "Invalid characters found in subscriberType")
    private String subscriberType;

    @NotNull
    @Pattern(regexp = "^[a-zA-Z0-9]", message = "Invalid characters found in caseId")
    private String caseId;

In above case en exception should be thrown whenever a request violate this String requirement (Providing an integer value to subscriberType). Also I need to validate them against invalid characters such as *,-,<,> etc. For this I have used @Pattern annotation.

My controller looks like this.

@Controller
public class MyController {

    @RequestMapping(value = "/my-controller/traceId/{Trace_ID}", method = RequestMethod.POST, produces =
            "application/json")
        public ResponseEntity<Object> startWork(@PathVariable Optional<String> Trace_ID,
                @Valid @RequestBody MyReqDto myReqDto)
            throws Exception {

I am using @Valid annotation and I have included maven dependency for hibernate-validator

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>4.0.2.GA</version>
</dependency>

<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>1.0.0.GA</version>
</dependency>

But the problem is, it does not validate my input and accept integer values for subscriberType and caseId.

Any help on this is highly appreciated.

Upvotes: 0

Views: 4523

Answers (2)

Nilucshan Siva
Nilucshan Siva

Reputation: 453

The issue in validating pattern was in my regex. Following solved the problem.

public class MyReqDto {
    @NotNull
    @Pattern(regexp = "^[a-zA-Z0-9]", message = "Invalid characters found in subscriberType")
    private String subscriberType;

    @NotNull
    @Pattern(regexp = "^[a-zA-Z0-9]", message = "Invalid characters found in caseId")
    private String caseId;

I noticed that by default declaring a request body parameter as string, and providing it with a integer value works fine, no exceptions thrown. However if we declare a request body parameter as integer and provide it with a string value, it will throw an exception.

Simply caseId="123" and caseId=123 have same effect in my request body since caseId is declared as a string.

Upvotes: 0

Debugger
Debugger

Reputation: 792

Not sure with acceptance criteria. I assume you are expecting like following patterns.

Regex Patterns

  • [A-Za-z ]* to match letters and spaces.

  • ".*[^0-9].*" to match Numbers

https://www.vogella.com/tutorials/JavaRegularExpressions/article.html

Upvotes: 1

Related Questions