Parameter validation via hibernate-validation in Java

Source: Internet
Author: User
Tags valid email address

In the development of Java server-side code, we will encounter the external parameters of the validity of validation, and Hibernate-validator provides some common parameter check annotations, we can use.
The hibernate-validator corresponding jar is introduced in 1.maven:

<dependency>    <groupId>org.hibernate</groupId>    <artifactid>hibernate-validator </artifactId>    <version>4.3.1.Final</version> </dependency>

2. Define the field to validate in the model (that is, the field cannot be empty and the maximum length is 14):

1234567891011121314151617181920212223242526272829303132333435 importjavax.validation.constraints.Pattern;import javax.validation.constraints.Size;importorg.hibernate.validator.constraints.NotEmpty;publicclassPayRequestDto {        /**     * 支付完成时间     **/    @NotEmpty(message="支付完成时间不能空")    @Size(max=14,message="支付完成时间长度不能超过{max}位")    privateString payTime;         /**     * 状态     **/    @Pattern(regexp = "0[0123]", message = "状态只能为00或01或02或03")    private String status;    publicString getPayTime() {        returnpayTime;    }    publicvoidsetPayTime(String payTime) {        this.payTime = payTime;    }    publicString getStatus() {        returnstatus;    }    publicvoidsetStatus(String status) {        this.status = status;    }}

3. Define the Validation tool class:

 Import Java.util.set;import Javax.validation.constraintviolation;import javax.validation.validation;import Javax.validation.validator;import Org.hibernate.validator.hibernatevalidator;import    Com.atai.framework.lang.appexception;public class Validationutils {/** * uses hibernate annotations for verification * */ private static Validator Validator = Validation. Byprovider (Hibernatevalidator.class). Configure (). FailFast (True    ). Buildvalidatorfactory (). Getvalidator ();     /** * Function Description: <br> *〈 Annotation Validation parameters 〉* * @param obj * @see [Related Classes/methods] (optional) * @since [Product/module version] (optional) */ public static <T> void validate (T obj) {set<constraintviolation<t>> constraintviolations = V        Alidator.validate (obj); Throw test Exception if (constraintviolations.size () > 0) {throw new Appexception ("0001", String.Format ("parameter check failed        :%s ", Constraintviolations.iterator (). Next (). GetMessage ())); }    }}

4. Call the tool class in the code to verify the parameters:

Validationutils.validate (requestdto);


The following is a description of some of the annotations in Hibernate-validator:

@AssertTrue For Boolean fields, this field can be true only
@AssertFalse The value of this field can only be false
@CreditCardNumber Make a rough verification of the credit card number
@DecimalMax Can only be less than or equal to this value
@DecimalMin Can only be greater than or equal to this value
@Digits (integer=,fraction=) Check whether it is a number of integers, fractions, digits of decimal digits
@Email Check to see if it is a valid email address
@Future Check if the date of the field is a date that belongs to the future
@Length (min=,max=) Checks whether the length of the owning field is between Min and Max and can only be used for strings
@Max The value of the field can only be less than or equal to the value
@Min The value of the field can only be greater than or equal to the value
@NotNull Cannot be null
@NotBlank cannot be empty, and whitespace is ignored when checking
@NotEmpty Cannot be empty, here the null is the empty string
@Null Check that the field is empty
@Past The date that the field was checked is in the past
@Pattern (regex=,flag=) The annotated element must conform to the specified regular expression
@Range (min=,max=,message=) The annotated element must be within the appropriate range
@Size (min=, max=) Checks whether the size of the field is between Min and Max, which can be a string, array, collection, map, and so on
@URL (Protocol=,host,port) Check if it is a valid URL, and if Protocol,host is provided, the URL must also meet the conditions provided
@Valid This annotation is used primarily for a field that contains a collection of other objects or a map or array, or a reference to a different object directly, so that the object referenced by the field is checked as well as the current object

Parameter validation via hibernate-validation in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.