9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series
Bean Validation Cheat Sheet
Introduction
This articleis focused on prcviding clear, simple, actionable guidance for providing Java Bean
Validation security functionality in your applications.
Bean validation (JSR303 aka Bean Validation 1.0 /JSR349 aka Bean Validation 1.1) isoneof the
most common ways to perform input validation in Java. It isan application layer agnostic
validation spec which provides the developer with the means to define a set of validation
constraints on a domain model and then perform validation of those constraints through out the
Various application tiers.
One advantage of this approach is that the validation constraints and the corresponding Validators
are only written once, thus reducing duptcation of effort and ensuring uniformity:
Typical Validation
lolitas
Custom Validation
calcd}
te uN eect
ETT
Cte Natl
Data Access
Gre uN leetcul
‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html ane9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series
Bean Validation
Tur ele
PT
pele Vac}
Setup
The examples in this quide use Hibemate Validator (the reference implementetion for Bean
Validation 1.1).
‘Add Hibemate Validator to your pom.xml:
org.hibernate
S.2.4.Final
Enable bean validtion support in Spring's context.xml:
For more info, please see the setup guide
Basics
‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html9123122, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series
In ofderto get started using Bean Validation, you must add validation constraints (ePattera,
evigits, @Min, OMex, @Size, éPast, GFuture, OCreditCardNunber , @Fmail, eURL ,etc) to
your model and then utiize the @va1id annotation when passing your model around in various
application layers.
Constraints can be applied in several places:
+ Fields
+ Properties
+ Classes
For Bean Validation 1.1 also on:
+ Parameters
+ Retum values
© Constructors
For the sake of simplicity all the examples below feature field constraints and all validation is
triggered by the controller. Refer to the Bean Validation documentation for a fulllist of exemples.
When it comes to ertor handing, the Hibemate Validator retums @ Bindingesutt object which
containsa List<0bjectError> . The examples belaw feature simplistic error handing, while a
Production ready application would have a more elaborate design that takes care of loggingand
error page redirection.
Predefined Constraints
@Pattem
Annotation:
@Pattern(regex=, flag=)
Data Type:
CharSequence
Use:
Checks if the annctated string matches the regular expression regex considering the given flag
match. Please visit OWASP Validation Regex Repository for other useful regex's.
‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html az9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series
Reference:
Documentation
Model:
import org.hibernate. validator .constraints.Pattern;
public class Article {
/1Constraint: Alpha Numeric article titles only using a regular expression
@Pattern(regexp = "[a-zA-20-9 |")
private String articleTitle;
public String gotarticleTitie() {
return articleTitle;
,
public void setArticleTitle(String articleTitle) {
this.articleTitle = articleTitle;
,
}
Controller:
import javax.validation. Valid;
import com.conpany..app.model.Article;
econtroller
public class ArticleController {
‘@RequestHapping(value = "/postarticle", method = RequestHethod. POST)
public @ResponseBody String postArticle(@Valid Article article, BindingResult
result,
HttpServietResponse response) {
if (result.hasErrors()) {
String errorMessage = "";
response..setStatus (Ht tpServletResponse..SC_BAD_REQUEST
List
errors = result.getAllerrors();
for(ObjectError e : errors) {
errorHessage 4= “ERROR: " + e.getDefaultMessage() ;
eee
}eise {
return “Validation Successful"
,
‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html9123122, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series
@bigits
Annotation:
epigits integers, fraction=)
Data Type:
BigDecinal, Biginteger , CharSequence, byte, short, int, long andthe respective wrappers
of the primitive types; Additionally supported by HV: any sub-type of Number
Use:
Checks whether the annctated value is a number having up to integer digits and fraction fractional
digits
Reference:
Documentation
Model:
import org.hibernate. validator .constraints.Digit:
public class Customer {
//Constraint: Age can only be 3 digits long or less
eDigite(integer = 3, fraction = 8)
private int age;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
Controller:
import javax.validation.Vali
import com.conpany .app.model.Custoner ;
econtroller
public class CustomerController {
‘ntps:ifcheatshectseries.owasp.orgicheatsheets/Bean_Validaion_Cheat_ Shoot. html9123/22, 8:25 AM Bean Valiation - OWASP Cheat Sheet Series
@RequestMapping(value = “/registerCustoner”, method = RequestMethod.POST)
public #ResponseBody String registerCustoner (@Valid Customer customer,
BindingResult result,
HttpServietResponse response) {
if (result.hasErrors())
‘String errorMessage = *";
response. setStatus(HttpServletResponse .SC_BAD_REQUEST) ;
List