简体   繁体   中英

Validating an object using spring validation for special characters

I am working on a springboot REST API and I have an object in the request which has around 50 fields. The requirement is for me to throw an invalid request if any of the field has an invalid special character. I was able to get it to work by adding @Pattern annotation over the fields inside the object to validate for a regular expression.

My problem is that these fields might grow and in the long term the maintenance would be a problem. Is there a way I can add a validator on the object itself so that it would validate all the fields inside that object, instead of manually adding it on all the fields inside that object. For example,

@Pattern(regexp="^[a-zA-Z0-9\s]*$")
Object abcField = null

Is there a better way to make this a more generic solution

There are plenty of ways to validate the parameters, before creating the object. I will introduce three of them:

1- The first and easiest way, would be implementing an ObjectValidator class which is responsible to validate parameters. It is obvious that you should call the validator manually in this way.

2- The next way I rarely use in my projects is validating objects in constructor . If the value of the parameters is not valid, you can throw an exception.

3- Implementing custom annotation is my favorite solution in this situation. You can implement your own annotation and put it above the data class. You need to use the following dependencies:

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.1.Final</version>
</dependency>

Your validator class should implement ConstraintValidator interface as well.

For more information to implement your own custom annotation you can read this link.

If you have more questions, do not hesitate to ask :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM