Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Usage

Validating Input Fields

Once you included this library and its dependencies into your web app, you may use the JSR-303 annotations to validate the user's input.

Code Block
java
java

public class Login
{
   @NotNull
   @Size(max=10)
   @Pattern(regexp = "[a-zA-Z]*")
   @Property @Persist
   private String userName;

   @NotNull 
   @Size(min=5, max=30)
   @Property @Persist
   private String password;

   void onSuccess()
   {
      // Login the user here
   }
}

You can event mix JSR-303 annotations and Tapestry's @Validate annotation.

Code Block
java
java

public class Login
{
   @NotNull
   @Validate("maxlength=10")
   @Pattern(regexp = "[a-zA-Z]*")
   @Property @Persist
   private String userName;

   @NotNull 
   @Validate("minlength=5,maxlength=30")
   @Property @Persist
   private String password;

   void onSuccess()
   {
      // Login the user here
   }
}

Next you have to pass the object to validate into the Form's parameter validate. In the following example the Form's fields are bound to the properties of the page Login. That's why we pass this, thus the page instance, into the parameter validate.

Code Block
xml
xml

<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_1_0.xsd">
   <body>
      <t:form validate="this">

         <t:errors/>

         <p>
            <t:textfield t:id="userName"/>
         </p>
         
         <p>
            <t:textfield t:id="password"/>
         </p>
         
         <p>
            <input type="submit" value="Login"/>
         </p>
      <t:form>
   </body>
</html>

Since the parameter validate defaults to the container of the Form component, we could also remove validate="this" in the example above.

Validating Beans with BeanEditForm

If you use the BeanEditForm component it's even easier to validate your beans. The only thing you have to do is to annotate your beans with JSR-303 annotations. If you are migrating from Tapestry's built-in validation mechanism to JSR-303 Bean Validation, you don't have to change your template at all.

Code Block
java
java

public class User
{
   @NotNull
   private String userName;

   @NotNull 
   @Validate("minlength=10")
   private String password;

   ...
}

Client-side Validation