<?xml version="1.0" encoding="UTF-8"?>
<!--
	~ JBoss, Home of Professional Open Source
	~ Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
	~ by the @authors tag. See the copyright.txt in the distribution for a
	~ full listing of individual contributors.
	~
	~ Licensed under the Apache License, Version 2.0 (the "License");
	~ you may not use this file except in compliance with the License.
	~ You may obtain a copy of the License at
	~ http://www.apache.org/licenses/LICENSE-2.0
	~ Unless required by applicable law or agreed to in writing, software
	~ distributed under the License is distributed on an "AS IS" BASIS,
	~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	~ See the License for the specific language governing permissions and
	~ limitations under the License.
-->
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../hv.ent">
%BOOK_ENTITIES;
]>
<chapter id="chapter-bean-constraints">
  <title>Declaring and validating bean constraints</title>

  <para>In this chapter you will learn how to declare (see <xref
  linkend="section-declaring-bean-constraints"/>) and validate (see <xref
  linkend="section-validating-bean-constraints"/>) bean constraints. <xref
  linkend="section-builtin-constraints"/> provides an overview of all built-in
  constraints coming with Hibernate Validator.</para>

  <para>If you are interested in applying constraints to method parameters and
  return values, refer to <xref linkend="chapter-method-constraints"/>.</para>

  <section id="section-declaring-bean-constraints">
    <title>Declaring bean constraints</title>

    <para>Constraints in Bean Validation are expressed via Java annotations.
    In this section you will learn how to enhance an object model with these
    annotations. There are the following three types of bean
    constraints:</para>

    <para><itemizedlist>
        <listitem>
          <para>field constraints</para>
        </listitem>

        <listitem>
          <para>property constraints</para>
        </listitem>

        <listitem>
          <para>class constraints</para>
        </listitem>
      </itemizedlist></para>

    <note>
      <para>Not all constraints can be placed on all of these levels. In fact,
      none of the default constraints defined by Bean Validation can be placed
      at class level. The <classname>java.lang.annotation.Target</classname>
      annotation in the constraint annotation itself determines on which
      elements a constraint can be placed. See <xref
      linkend="validator-customconstraints"/> for more information.</para>
    </note>

    <section>
      <title>Field-level constraints</title>

      <para>Constraints can be expressed by annotating a field of a class.
      <xref linkend="example-field-level"/> shows a field level configuration
      example:</para>

      <example id="example-field-level">
        <title>Field-level constraints</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.fieldlevel;

public class Car {

	@NotNull
	private String manufacturer;

	@AssertTrue
	private boolean isRegistered;

	public Car(String manufacturer, boolean isRegistered) {
		this.manufacturer = manufacturer;
		this.isRegistered = isRegistered;
	}

	//getters and setters...
}</programlisting>
      </example>

      <para>When using field-level constraints field access strategy is used
      to access the value to be validated. This means the validation engine
      directly accesses the instance variable and does not invoke the property
      accessor method even if such an accessor exists.</para>

      <para>Constraints can be applied to fields of any access type (public,
      private etc.). Constraints on static fields are not supported,
      though.</para>

      <tip>
        <para>When validating byte code enhanced objects property level
        constraints should be used, because the byte code enhancing library
        won't be able to determine a field access via reflection.</para>
      </tip>
    </section>

    <section>
      <title>Property-level constraints</title>

      <para>If your model class adheres to the <ulink type=""
      url="http://java.sun.com/javase/technologies/desktop/javabeans/index.jsp">JavaBeans</ulink>
      standard, it is also possible to annotate the properties of a bean class
      instead of its fields. <xref linkend="example-property-level"/> uses the
      same entity as in <xref linkend="example-field-level"/>, however,
      property level constraints are used.</para>

      <example id="example-property-level">
        <title>Property-level constraints</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.propertylevel;

public class Car {

	private String manufacturer;

	private boolean isRegistered;

	public Car(String manufacturer, boolean isRegistered) {
		this.manufacturer = manufacturer;
		this.isRegistered = isRegistered;
	}

	@NotNull
	public String getManufacturer() {
		return manufacturer;
	}

	public void setManufacturer(String manufacturer) {
		this.manufacturer = manufacturer;
	}

	@AssertTrue
	public boolean isRegistered() {
		return isRegistered;
	}

	public void setRegistered(boolean isRegistered) {
		this.isRegistered = isRegistered;
	}
}</programlisting>
      </example>

      <note>
        <para>The property's getter method has to be annotated, not its
        setter. That way also read-only properties can be constrained which
        have no setter method.</para>
      </note>

      <para>When using property level constraints property access strategy is
      used to access the value to be validated, i.e. the validation engine
      accesses the state via the property accessor method.</para>

      <tip>
        <para>It is recommended to stick either to field
        <emphasis>or</emphasis> property annotations within one class. It is
        not recommended to annotate a field <emphasis>and</emphasis> the
        accompanying getter method as this would cause the field to be
        validated twice.</para>
      </tip>
    </section>

    <section>
      <title id="validator-usingvalidator-classlevel">Class-level
      constraints</title>

      <para>Last but not least, a constraint can also be placed on the class
      level. In this case not a single property is subject of the validation
      but the complete object. Class-level constraints are useful if the
      validation depends on a correlation between several properties of an
      object.</para>

      <para>The <classname>Car</classname> class in <xref
      linkend="example-class-level"/> has the two attributes
      <varname>seatCount</varname> and <varname>passengers</varname> and it
      should be ensured that the list of passengers has not more entries than
      seats are available. For that purpose the
      <classname>@ValidPassengerCount</classname> constraint is added on the
      class level. The validator of that constraint has access to the complete
      <classname>Car</classname> object, allowing to compare the numbers of
      seats and passengers.</para>

      <para>Refer to <xref linkend="section-class-level-constraints"/> to
      learn in detail how to implement this custom constraint.</para>

      <example id="example-class-level">
        <title>Class-level constraint</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.classlevel;

@ValidPassengerCount
public class Car {

	private int seatCount;

	private List&lt;Person&gt; passengers;

	//...
}</programlisting>
      </example>
    </section>

    <section id="section-constraint-inheritance">
      <title>Constraint inheritance</title>

      <para>When a class implements an interface or extends another class, all
      constraint annotations declared on the supertype apply in the same
      manner as the constraints specified on the class itself. To make things
      clearer let's have a look at the following example:</para>

      <example>
        <title>Constraint inheritance</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.inheritance;

public class Car {

	private String manufacturer;

	@NotNull
	public String getManufacturer() {
		return manufacturer;
	}

	//...
}</programlisting>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.inheritance;

public class RentalCar extends Car {

	private String rentalStation;

	@NotNull
	public String getRentalStation() {
		return rentalStation;
	}

	//...
}</programlisting>
      </example>

      <para>Here the class <classname>RentalCar</classname> is a subclass of
      <classname>Car</classname> and adds the property
      <property>rentalStation</property>. If an instance of
      <classname>RentalCar</classname> is validated, not only the
      <classname>@NotNull</classname> constraint on
      <property>rentalStation</property> is evaluated, but also the constraint
      on <property>manufacturer</property> from the parent class.</para>

      <para>The same would be true, if <classname>Car</classname> was not a
      superclass but an interface implemented by
      <classname>RentalCar</classname>.</para>

      <para>Constraint annotations are aggregated if methods are overridden.
      So if <classname>RentalCar</classname> overrode the
      <methodname>getManufacturer()</methodname> method from
      <classname>Car</classname>, any constraints annotated at the overriding
      method would be evaluated in addition to the
      <classname>@NotNull</classname> constraint from the superclass.</para>
    </section>

    <section id="section-object-graph-validation">
      <title>Object graphs</title>

      <para>The Bean Validation API does not only allow to validate single
      class instances but also complete object graphs (cascaded validation).
      To do so, just annotate a field or property representing a reference to
      another object with <classname>@Valid</classname> as demonstrated in
      <xref linkend="example-cascaded-validation"/>.</para>

      <example id="example-cascaded-validation">
        <title>Cascaded validation</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.objectgraph;

public class Car {

	@NotNull
	@Valid
	private Person driver;

	//...
}</programlisting>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.objectgraph;

public class Person {

	@NotNull
	private String name;

	//...
}</programlisting>
      </example>

      <para>If an instance of <classname>Car</classname> is validated, the
      referenced <classname>Person</classname> object will be validated as
      well, as the <property>driver</property> field is annotated with
      <classname>@Valid</classname>. Therefore the validation of a
      <classname>Car</classname> will fail if the <property>name</property>
      field of the referenced <classname>Person</classname> instance is
      <code>null</code>.</para>

      <para>The validation of object graphs is recursive, i.e. if a reference
      marked for cascaded validation points to an object which itself has
      properties annotated with <classname>@Valid</classname>, these
      references will be followed up by the validation engine as well. The
      validation engine will ensure that no infinite loops occur during
      cascaded validation, for example if two objects hold references to each
      other.</para>

      <para>Note that <literal>null</literal> values are getting ignored
      during cascaded validation.</para>

      <para>Object graph validation also works for collection-typed fields.
      That means any attributes that</para>

      <itemizedlist>
        <listitem>
          <para>are arrays</para>
        </listitem>

        <listitem>
          <para>implement <classname>java.lang.Iterable</classname>
          (especially <classname>Collection</classname>,
          <classname>List</classname> and <classname>Set</classname>)</para>
        </listitem>

        <listitem>
          <para>implement <classname>java.util.Map</classname></para>
        </listitem>
      </itemizedlist>

      <para>can be annotated with <classname>@Valid</classname>, which will
      cause each contained element to be validated, when the parent object is
      validated.</para>

      <example id="example-cascaded-validation-list">
        <title>Cascaded validation of a collection</title>

        <programlisting language="JAVA" role="JAVA">package org.hibernate.validator.referenceguide.chapter02.objectgraph.list;

public class Car {

	@NotNull
	@Valid
	private List&lt;Person&gt; passengers = new ArrayList&lt;Person&gt;();

	//...
}</programlisting>
      </example>

      <para>So when validating an instance of the <classname>Car</classname>
      class shown in <xref linkend="example-cascaded-validation-list"/>, a
      <classname>ConstraintViolation</classname> will be created, if any of
      the <classname>Person</classname> objects contained in the
      <property>passengers</property> list has a <code>null</code>
      name.</para>
    </section>
  </section>

  <section id="section-validating-bean-constraints">
    <title>Validating bean constraints</title>

    <para>The <classname>Validator</classname> interface is the most important
    object in Bean Validation. The next section shows how to obtain an
    <classname>Validator</classname> instance. Afterwards you'll learn how to
    use the different methods of the <classname>Validator</classname>
    interface.</para>

    <section id="section-obtaining-validator">
      <title>Obtaining a <classname>Validator</classname> instance</title>

      <para>The first step towards validating an entity instance is to get
      hold of a <classname>Validator</classname> instance. The road to this
      instance leads via the <classname>Validation</classname> class and a
      <classname>ValidatorFactory</classname>. The easiest way is to use the
      static method
      <methodname>Validation#buildDefaultValidatorFactory()</methodname>:</para>

      <example>
        <title>Validation#buildDefaultValidatorFactory()</title>

        <programlisting language="JAVA" role="JAVA">ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();</programlisting>
      </example>

      <para>This bootstraps a validator in the default configuration. Refer to
      <xref linkend="chapter-bootstrapping"/> to learn more about the
      different bootstrapping methods and how to obtain a specifically
      configured <classname>Validator</classname> instance.</para>
    </section>

    <section>
      <title>Validator methods</title>

      <para>The <classname>Validator</classname> interface contains three
      methods that can be used to either validate entire entities or just
      single properties of the entity.</para>

      <para>All three methods return a
      <classname>Set&lt;ConstraintViolation&gt;</classname>. The set is empty,
      if the validation succeeds. Otherwise a
      <classname>ConstraintViolation</classname> instance is added for each
      violated constraint.</para>

      <para>All the validation methods have a var-args parameter which can be
      used to specify, which validation groups shall be considered when
      performing the validation. If the parameter is not specified the default
      validation group
      (<classname>javax.validation.groups.Default</classname>) is used. The
      topic of validation groups is discussed in detail in <xref
      linkend="chapter-groups"/>.</para>

      <section>
        <title><methodname>Validator#validate()</methodname></title>

        <para>Use the <methodname>validate()</methodname> method to perform
        validation of all constraints of a given bean. <xref
        linkend="example-validator-validate"/> shows the validation of an
        instance of the <classname>Car</classname> class from <xref
        linkend="example-property-level"/> which fails to satisfy the
        <classname>@NotNull</classname> constraint on the
        <varname>manufacturer</varname> property. The validation call
        therefore returns one <classname>ConstraintViolation</classname>
        object.</para>

        <example id="example-validator-validate">
          <title>Using <methodname>Validator#validate()</methodname></title>

          <programlisting language="JAVA" role="JAVA">Car car = new Car( null, true );

Set&lt;ConstraintViolation&lt;Car&gt;&gt; constraintViolations = validator.validate( car );

assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );</programlisting>
        </example>
      </section>

      <section>
        <title><methodname>Validator#validateProperty()</methodname></title>

        <para>With help of the <methodname>validateProperty()</methodname> you
        can validate a single named property of a given object. The property
        name is the JavaBeans property name.</para>

        <example>
          <title>Using
          <methodname>Validator#validateProperty()</methodname></title>

          <programlisting language="JAVA" role="JAVA">Car car = new Car( null, true );

Set&lt;ConstraintViolation&lt;Car&gt;&gt; constraintViolations = validator.validateProperty(
		car,
		"manufacturer"
);

assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );</programlisting>
        </example>
      </section>

      <section>
        <title><methodname>Validator#validateValue()</methodname></title>

        <para>By using the <methodname>validateValue() </methodname>method you
        can check whether a single property of a given class can be validated
        successfully, if the property had the specified value:</para>

        <example>
          <title>Using
          <methodname>Validator#validateValue()</methodname></title>

          <programlisting language="JAVA" role="JAVA">Set&lt;ConstraintViolation&lt;Car&gt;&gt; constraintViolations = validator.validateValue(
		Car.class,
		"manufacturer",
		null
);

assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );</programlisting>
        </example>

        <note>
          <para><classname>@Valid</classname> is not honored by
          <methodname>validateProperty()</methodname> or
          <methodname>validateValue()</methodname>.</para>
        </note>

        <para><methodname>Validator#validateProperty()</methodname> is for
        example used in the integration of Bean Validation into JSF 2 (see
        <xref linkend="section-presentation-layer"/>) to perform a validation
        of the values entered into a form before they are propagated to the
        model.</para>
      </section>
    </section>

    <section id="section-constraint-violation-methods">
      <title><classname>ConstraintViolation</classname> methods</title>

      <para>Now it is time to have a closer look at what a
      <classname>ConstraintViolation</classname> is. Using the different
      methods of <classname>ConstraintViolation</classname> a lot of useful
      information about the cause of the validation failure can be determined.
      <xref linkend="table-constraint-violation"/> gives an overview of these
      methods. The values in the "Example" column refer to <xref
      linkend="example-validator-validate"/>.</para>

      <table id="table-constraint-violation">
        <title>The various <classname>ConstraintViolation</classname>
        methods</title>

        <tgroup cols="3">
          <thead>
            <row>
              <entry>Method</entry>

              <entry>Usage</entry>

              <entry>Example</entry>
            </row>
          </thead>

          <tbody>
            <row>
              <entry><methodname>getMessage()</methodname></entry>

              <entry>The interpolated error message</entry>

              <entry>"may not be null"</entry>
            </row>

            <row>
              <entry><methodname>getMessageTemplate()</methodname></entry>

              <entry>The non-interpolated error message</entry>

              <entry>"{... NotNull.message}"</entry>
            </row>

            <row>
              <entry><methodname>getRootBean()</methodname></entry>

              <entry>The root bean being validated</entry>

              <entry><varname>car</varname></entry>
            </row>

            <row>
              <entry><methodname>getRootBeanClass()</methodname></entry>

              <entry>The class of the root bean being validated</entry>

              <entry><classname>Car.class</classname></entry>
            </row>

            <row>
              <entry><methodname>getLeafBean()</methodname></entry>

              <entry>If a bean constraint, the bean instance the constraint is
              applied on; If a property constraint, the bean instance hosting
              the property the constraint is applied on</entry>

              <entry><varname>car</varname></entry>
            </row>

            <row>
              <entry><methodname>getPropertyPath()</methodname></entry>

              <entry>The property path to the validated value from root
              bean</entry>

              <entry>contains one node with kind
              <classname>PROPERTY</classname> and name "manufacturer"</entry>
            </row>

            <row>
              <entry><methodname>getInvalidValue()</methodname></entry>

              <entry>The value failing to pass the constraint</entry>

              <entry><literal>null</literal></entry>
            </row>

            <row>
              <entry><methodname>getConstraintDescriptor()</methodname></entry>

              <entry>Constraint metadata reported to fail</entry>

              <entry>descriptor for <classname>@NotNull</classname></entry>
            </row>
          </tbody>
        </tgroup>
      </table>
    </section>
  </section>

  <section id="section-builtin-constraints">
    <title>Built-in constraints</title>

    <para>Hibernate Validator comprises a basic set of commonly used
    constraints. These are foremost the constraints defined by the Bean
    Validation specification (see <xref linkend="table-spec-constraints"/>).
    Additionally, Hibernate Validator provides useful custom constraints (see
    <xref linkend="table-custom-constraints"/> and <xref
    linkend="table-custom-country-constraints"/>).</para>

    <section id="validator-defineconstraints-spec">
      <title>Bean Validation constraints</title>

      <para><xref linkend="table-spec-constraints"/> shows purpose and
      supported data types of all constraints specified in the Bean Validation
      API. All these constraints apply to the field/property level, there are
      no class-level constraints defined in the Bean Validation specification.
      If you are using the Hibernate object-relational mapper, some of the
      constraints are taken into account when creating the DDL for your model
      (see column "Hibernate metadata impact").</para>

      <note>
        <para>Hibernate Validator allows some constraints to be applied to
        more data types than required by the Bean Validation specification
        (e.g. <classname>@Max</classname> can be applied to
        <classname>Strings</classname>). Relying on this feature can impact
        portability of your application between Bean Validation
        providers.</para>
      </note>

      <table id="table-spec-constraints">
        <title>Bean Validation constraints</title>

        <tgroup cols="4">
          <colspec align="left" colwidth="1*"/>

          <colspec align="left" colwidth="2*"/>

          <colspec align="left" colwidth="2*"/>

          <colspec align="left" colwidth="1*"/>

          <thead>
            <row>
              <entry>Annotation</entry>

              <entry>Supported data types</entry>

              <entry>Use</entry>

              <entry>Hibernate metadata impact</entry>
            </row>
          </thead>

          <tbody valign="top">
            <row>
              <entry><classname>@AssertFalse</classname></entry>

              <entry><classname>Boolean</classname>,
              <classname>boolean</classname></entry>

              <entry>Checks that the annotated element is
              <constant>false</constant></entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@AssertTrue</classname></entry>

              <entry><classname>Boolean</classname>,
              <classname>boolean</classname></entry>

              <entry>Checks that the annotated element is
              <constant>true</constant></entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@DecimalMax(value=,</classname>
              <classname>inclusive=)</classname></entry>

              <entry><classname>BigDecimal</classname>,
              <classname>BigInteger</classname>,
              <classname>CharSequence</classname>,
              <classname>byte</classname>, <classname>short</classname>,
              <classname>int</classname>, <classname>long</classname> and the
              respective wrappers of the primitive types; Additionally
              supported by HV: any sub-type of
              <classname>Number</classname></entry>

              <entry>Checks whether the annotated value is less than the
              specified maximum, when <parameter>inclusive=false</parameter>.
              Otherwise whether the value is less than or equal to the
              specified maximum. The parameter <parameter>value</parameter> is
              the string representation of the max value according to the
              <classname>BigDecimal</classname> string representation.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@DecimalMin(value=,</classname>
              <classname>inclusive=)</classname></entry>

              <entry><classname>BigDecimal</classname>,
              <classname>BigInteger</classname>,
              <classname>CharSequence</classname>,
              <classname>byte</classname>, <classname>short</classname>,
              <classname>int</classname>, <classname>long</classname> and the
              respective wrappers of the primitive types; Additionally
              supported by HV: any sub-type of
              <classname>Number</classname></entry>

              <entry>Checks whether the annotated value is larger than the
              specified minimum, when <parameter>inclusive=false</parameter>.
              Otherwise whether the value is larger than or equal to the
              specified minimum. The parameter <parameter>value</parameter> is
              the string representation of the min value according to the
              <classname>BigDecimal</classname> string representation.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Digits(integer=,</classname>
              <classname>fraction=)</classname></entry>

              <entry><classname>BigDecimal</classname>,
              <classname>BigInteger</classname>,
              <classname>CharSequence</classname>,
              <classname>byte</classname>, <classname>short</classname>,
              <classname>int</classname>, <classname>long</classname> and the
              respective wrappers of the primitive types; Additionally
              supported by HV: any sub-type of
              <classname>Number</classname></entry>

              <entry>Checks whether the annoted value is a number having up to
              <literal>integer</literal> digits and
              <literal>fraction</literal> fractional digits</entry>

              <entry>Defines column precision and scale</entry>
            </row>

            <row>
              <entry><classname>@Future</classname></entry>

              <entry><classname>java.util.Date</classname>,
              <classname>java.util.Calendar</classname>; Additionally
              supported by HV, if the <ulink
              url="http://joda-time.sourceforge.net/">Joda Time</ulink>
              date/time API is on the class path: any implementations of
              <classname>ReadablePartial</classname> and
              <classname>ReadableInstant</classname></entry>

              <entry>Checks whether the annotated date is in the
              future</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Max(value=)</classname></entry>

              <entry><classname>BigDecimal</classname>,
              <classname>BigInteger</classname>, <classname>byte</classname>,
              <classname>short</classname>, <classname>int</classname>,
              <classname>long</classname> and the respective wrappers of the
              primitive types; Additionally supported by HV: any sub-type of
              <classname>CharSequence</classname> (the numeric value
              represented by the character sequence is evaluated), any
              sub-type of <classname>Number</classname></entry>

              <entry>Checks whether the annotated value is less than or equal
              to the specified maximum</entry>

              <entry>Adds a check constraint on the column</entry>
            </row>

            <row>
              <entry><classname>@Min(value=)</classname></entry>

              <entry><classname>BigDecimal</classname>,
              <classname>BigInteger</classname>, <classname>byte</classname>,
              <classname>short</classname>, <classname>int</classname>,
              <classname>long</classname> and the respective wrappers of the
              primitive types; Additionally supported by HV: any sub-type of
              <classname>CharSequence</classname> (the numeric value
              represented by the char sequence is evaluated), any sub-type of
              <classname>Number</classname></entry>

              <entry>Checks whether the annotated value is higher than or
              equal to the specified minimum</entry>

              <entry>Adds a check constraint on the column</entry>
            </row>

            <row>
              <entry><classname>@NotNull</classname></entry>

              <entry>Any type</entry>

              <entry>Checks that the annotated value is not
              <constant>null.</constant></entry>

              <entry>Column(s) are not nullable</entry>
            </row>

            <row>
              <entry><classname>@Null</classname></entry>

              <entry>Any type</entry>

              <entry>Checks that the annotated value is
              <constant>null</constant></entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Past</classname></entry>

              <entry><classname>java.util.Date</classname>,
              <classname>java.util.Calendar</classname>; Additionally
              supported by HV, if the <ulink
              url="http://joda-time.sourceforge.net/">Joda Time</ulink>
              date/time API is on the class path: any implementations of
              <classname>ReadablePartial</classname> and
              <classname>ReadableInstant</classname></entry>

              <entry>Checks whether the annotated date is in the past</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Pattern(regex=,</classname>
              <classname>flag=)</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks if the annotated string matches the regular
              expression <parameter>regex</parameter> considering the given
              flag <parameter>match</parameter></entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Size(min=, max=)</classname></entry>

              <entry><classname>CharSequence</classname>,
              <classname>Collection</classname>, <classname>Map</classname>
              and <classname>arrays</classname></entry>

              <entry>Checks if the annotated element's size is between min and
              max (inclusive)</entry>

              <entry>Column length will be set to
              <parameter>max</parameter></entry>
            </row>

            <row>
              <entry><classname>@Valid</classname></entry>

              <entry>Any non-primitive type</entry>

              <entry>Performs validation recursively on the associated object.
              If the object is a collection or an array, the elements are
              validated recursively. If the object is a map, the value
              elements are validated recursively.</entry>

              <entry>None</entry>
            </row>
          </tbody>
        </tgroup>
      </table>

      <note>
        <para>On top of the parameters indicated in <xref
        linkend="table-spec-constraints"/> each constraint has the parameters
        <parameter>message</parameter>, <parameter>groups</parameter> and
        <parameter>payload</parameter>. This is a requirement of the Bean
        Validation specification.</para>
      </note>
    </section>

    <section id="validator-defineconstraints-hv-constraints">
      <title>Additional constraints</title>

      <para>In addition to the constraints defined by the Bean Validation API
      Hibernate Validator provides several useful custom constraints which are
      listed in <xref linkend="table-custom-constraints"/>. With one exception
      also these constraints apply to the field/property level, only
      <classname>@ScriptAssert</classname> is a class-level constraint.</para>

      <table id="table-custom-constraints">
        <title>Custom constraints</title>

        <tgroup cols="4">
          <colspec align="left"/>

          <colspec align="left"/>

          <colspec align="left"/>

          <colspec align="left"/>

          <thead>
            <row>
              <entry>Annotation</entry>

              <entry>Supported data types</entry>

              <entry>Use</entry>

              <entry>Hibernate metadata impact</entry>
            </row>
          </thead>

          <tbody valign="top">
            <row>
              <entry><classname>@CreditCardNumber</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks that the annotated character sequence passes the
              Luhn checksum test. Note, this validation aims to check for user
              mistakes, not credit card validity! See also <ulink
              url="http://www.merriampark.com/anatomycc.htm">Anatomy of Credit
              Card Numbers</ulink>.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@EAN</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks that the annotated character sequence is a valid
              <ulink
              url="http://en.wikipedia.org/wiki/International_Article_Number_%28EAN%29">EAN</ulink>
              barcode. <constant>type</constant> determines the type of
              barcode. The default is EAN-13.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Email</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks whether the specified character sequence is a
              valid email address. The optional parameters
              <parameter>regexp</parameter> and <parameter>flags</parameter>
              allow to specify an additional regular expression (including
              regular expression flags) which the email must match.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Length(min=, max=)</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Validates that the annotated character sequence is
              between <parameter>min</parameter> and
              <parameter>max</parameter> included</entry>

              <entry>Column length will be set to
              <parameter>max</parameter></entry>
            </row>

            <row>
              <entry><classname>@LuhnCheck(</classname><classname>startIndex=,</classname>
              <classname>endIndex=,</classname>
              <classname>checkDigitIndex=,</classname>
              <classname>ignoreNonDigitCharacters=)</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks that the digits within the annotated character
              sequence pass the Luhn checksum algorithm (see also <ulink
              url="http://en.wikipedia.org/wiki/Luhn_algorithm">Luhn
              algorithm</ulink>). <constant>startIndex</constant> and
              <constant>endIndex</constant> allow to only run the algorithm on
              the specified sub-string. <constant>checkDigitIndex</constant>
              allows to use an arbitrary digit within the character sequence
              as the check digit. If not specified it is assumed that the
              check digit is part of the specified range. Last but not least,
              <constant>ignoreNonDigitCharacters</constant> allows to ignore
              non digit characters.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Mod10Check(multiplier=,</classname>
              <classname>weight=, startIndex=,</classname>
              <classname>endIndex=,</classname>
              <classname>checkDigitIndex=,</classname>
              <classname>ignoreNonDigitCharacters=)</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks that the digits within the annotated character
              sequence pass the generic mod 10 checksum algorithm.
              <constant>multiplier</constant> determines the multiplier for
              odd numbers (defaults to 3), <constant>weight</constant> the
              weight for even numbers (defaults to 1).
              <constant>startIndex</constant> and
              <constant>endIndex</constant> allow to only run the algorithm on
              the specified sub-string. <constant>checkDigitIndex</constant>
              allows to use an arbitrary digit within the character sequence
              as the check digit. If not specified it is assumed that the
              check digit is part of the specified range. Last but not least,
              <constant>ignoreNonDigitCharacters</constant> allows to ignore
              non digit characters.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Mod11Check(threshold=,</classname>
              <classname>startIndex=, endIndex=,</classname>
              <classname>checkDigitIndex=,</classname>
              <classname>ignoreNonDigitCharacters=,</classname>
              <classname>treatCheck10As=,</classname>
              <classname>treatCheck11As=)</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks that the digits within the annotated character
              sequence pass the mod 11 checksum algorithm.
              <constant>threshold</constant> specifies the threshold for the
              mod11 multiplier growth; if no value is specified the multiplier
              will grow indefinitely. <classname>treatCheck10As</classname>
              and <classname>treatCheck11As</classname> specify the check
              digits to be used when the mod 11 checksum equals 10 or 11,
              respectively. Default to X and 0, respectively.
              <constant>startIndex</constant>, <constant>endIndex</constant>
              a<constant>checkDigitIndex</constant> and
              <constant>ignoreNonDigitCharacters</constant> carry the same
              semantics as in <classname>@Mod10Check</classname>.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@NotBlank</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks that the annotated character sequence is not null
              and the trimmed length is greater than 0. The difference to
              <classname>@NotEmpty</classname> is that this constraint can
              only be applied on strings and that trailing whitespaces are
              ignored.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@NotEmpty</classname></entry>

              <entry><classname>CharSequence</classname>,
              <classname>Collection</classname>, <classname>Map</classname>
              and arrays</entry>

              <entry>Checks whether the annotated element is not
              <constant>null</constant> nor empty</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@Range(min=, max=)</classname></entry>

              <entry><classname>BigDecimal</classname>,
              <classname>BigInteger</classname>,
              <classname>CharSequence</classname>,
              <classname>byte</classname>, <classname>short</classname>,
              <classname>int</classname>, <classname>long</classname> and the
              respective wrappers of the primitive types</entry>

              <entry>Checks whether the annotated value lies between
              (inclusive) the specified minimum and maximum</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@SafeHtml(whitelistType=,</classname>
              <classname>additionalTags=,
              additionalTagsWithAttributes=)</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry><para>Checks whether the annotated value contains
              potentially malicious fragments such as
              <code>&lt;script/&gt;</code>. In order to use this constraint,
              the <ulink url="http://jsoup.org/">jsoup</ulink> library must be
              part of the class path. </para><para>With the
              <parameter>whitelistType</parameter> attribute a predefined
              whitelist type can be chosen which can be refined via
              <methodname>additionalTags</methodname> or
              <methodname>additionalTagsWithAttributes</methodname>. The
              former allows to add tags without any attributes, whereas the
              latter allows to specify tags and optionally allowed attributes
              using the annotation
              <classname>@SafeHtml.Tag</classname>.</para></entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@ScriptAssert(lang=,</classname>
              <classname>script=, alias=)</classname></entry>

              <entry>Any type</entry>

              <entry>Checks whether the given script can successfully be
              evaluated against the annotated element. In order to use this
              constraint, an implementation of the Java Scripting API as
              defined by JSR 223 ("Scripting for the
              Java<superscript>TM</superscript> Platform") must part of the
              class path. The expressions to be evaluated can be written in
              any scripting or expression language, for which a JSR 223
              compatible engine can be found in the class path.</entry>

              <entry>None</entry>
            </row>

            <row>
              <entry><classname>@URL(protocol=,</classname> <classname>host=,
              port=</classname> <classname>regexp=,
              flags=)</classname></entry>

              <entry><classname>CharSequence</classname></entry>

              <entry>Checks if the annotated character sequence is a valid URL
              according to RFC2396. If any of the optional parameters
              <parameter>protocol</parameter>, <parameter>host</parameter> or
              <parameter>port</parameter> are specified, the corresponding URL
              fragments must match the specified values. The optional
              parameters <parameter>regexp</parameter> and
              <parameter>flags</parameter> allow to specify an additional
              regular expression (including regular expression flags) which
              the URL must match.</entry>

              <entry>None</entry>
            </row>
          </tbody>
        </tgroup>
      </table>

      <section>
        <title>Country specific constraints</title>

        <para>Hibernate Validator offers also some country specific
        constraints, e.g. for the validation of social security numbers. <note>
            <para>If you have to implement a country specific constraint,
            consider making it a contribution to Hibernate Validator!</para>
          </note></para>

        <table id="table-custom-country-constraints">
          <title>Custom country specific constraints</title>

          <tgroup cols="5">
            <colspec align="left"/>

            <colspec align="left"/>

            <colspec align="left"/>

            <colspec align="left"/>

            <colspec align="left"/>

            <thead>
              <row>
                <entry>Annotation</entry>

                <entry>Supported data types</entry>

                <entry>Use</entry>

                <entry>Country</entry>

                <entry>Hibernate metadata impact</entry>
              </row>
            </thead>

            <tbody valign="top">
              <row>
                <entry><classname>@CNPJ</classname></entry>

                <entry><classname>CharSequence</classname></entry>

                <entry>Checks that the annotated character sequence represents
                a Brazilian corporate tax payer registry number (Cadastro de
                Pessoa Juríeddica)</entry>

                <entry>Brazil</entry>

                <entry>None</entry>
              </row>

              <row>
                <entry><classname>@CPF</classname></entry>

                <entry><classname>CharSequence</classname></entry>

                <entry>Checks that the annotated character sequence represents
                a Brazilian individual taxpayer registry number (Cadastro de
                Pessoa Fídsica)</entry>

                <entry>Brazil</entry>

                <entry>None</entry>
              </row>

              <row>
                <entry><classname>@TituloEleitoral</classname></entry>

                <entry><classname>CharSequence</classname></entry>

                <entry>Checks that the annotated character sequence represents
                a Brazilian voter ID card number (<ulink
                url="http://ghiorzi.org/cgcancpf.htm">Título
                Eleitoral</ulink>)</entry>

                <entry>Brazil</entry>

                <entry>None</entry>
              </row>
            </tbody>
          </tgroup>
        </table>

        <tip>
          <para>In some cases neither the Bean Validation constraints nor the
          custom constraints provided by Hibernate Validator will fulfill your
          requirements. In this case you can easily write your own constraint.
          You can find more information in <xref
          linkend="validator-customconstraints"/>.</para>
        </tip>
      </section>
    </section>
  </section>
</chapter>
