Creating a form with validation and tooltips

This sample shows how to make a create and edit form with validation and tooltips. It demonstrates regular expression validation as well as a more complex validation using a groovy script.

Download the sample in xar format

You will need to add ValidationSample.Translations to your translations bundles in the Advanced section of the global preferences.

Known issues

The following patches need to be applied on top of XWiki 1.3.2 or later (until we fix them, probably for XE 1.5):

How does my form look like when validation errors are shown

formvalidationedit.png

Documents, Class and Scripts:

  • ValidationSample.WebHome Home page where you can create a new document and access the existing ones
  • ValidationSample.ValidationSampleClassSheet Sheet presenting the document in create, edit and view mode including validation error messages
  • ValidationSample.CreateDoc Page called on the submission of the create document form. This will validate and show the form with errors or will save the document.
  • ValidationSample.ValidationSampleClass Class with definitions of fields, regular expressions and error message translations strings
  • ValidationSample.ValidationGroovy Groovy validation script for complex validations
  • ValidationSample.ValidationSampleClassTemplate Template of a document
  • ValidationSample.Translations Translations of the texts, tooltips and error messages. This shows an example of the naming conventions for tooltips and pretty names
  • ValidationSample.Val ValidationSample.Val_0 ValidationSample.Val_1 Sample documents

How to create validations using regular expressions

To create validation first you need to declare your class and set the regulare expression to validate the fields you want to validate.

The following code should be called to launch a validation on a document

## this will launch a validation on a document. All errors are added to the context
$doc.validate()

The following code is need in the form to launch the validation for a standard Save to validate the form

<input type="hidden" name="xvalidate" value="1" />

Pay attention to the Validation Regular Expression and Validation Message fields. The first one is a Java Regular Expression pattern and the second one is a translation string:

  • first_name
    • /.{2,20}/ -> field needs to be between 2 characters and 20 characters.
    • val_firstname_toolong -> XWiki will lookup this translation string in the translations pages
  • last_name
    • /.{2,20}/ -> field needs to be between 2 characters and 20 characters.
  • email
    • /.*@.*\.com/ -> field must contain @ and finish with .com
  • age
    • no validation set for age. This will be handled by the groovy script
  • usphone
    • /[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]/ -> the phone number must be made of digits separated by - in the form 000-000-0000
formvalidationclass.png

How to create validations using a groovy script

To create complex validation you can use a groovy script.

The following code should be called to launch a validation on a document

## add the groovy script to the validation (the xvalidation parameter in the request also works to set the groovy script validation)
$doc.setValidationScript("ValidationSample.ValidationGroovy")
## this will launch a validation on a document. All errors are added to the context
$doc.validate()

The following code is need in the form to launch the validation on a standard Save of a document:

## Force validation
<input type="hidden" name="xvalidate" value="1" />
## Set the validation script. This is necessary until the bug http://jira.xwiki.org/jira/browse/XWIKI-2382
<input type="hidden" name="xvalidation" value="ValidationSample.ValidationGroovy" />

Here is the sample groovy script:

import com.xpn.xwiki.validation.*;
import com.xpn.xwiki.*;
import com.xpn.xwiki.doc.*;
import com.xpn.xwiki.objects.*;

public class Val implements XWikiValidationInterface  {
    public boolean validateDocument(XWikiDocument doc, XWikiContext context) {
      // You can log in the app server output to check your code
      // System.out.println("validation is called");
      def res = true;
      def obj = doc.getObject("ValidationSample.ValidationSampleClass");
      def first_name = obj.getStringValue("first_name");
      def last_name = obj.getStringValue("last_name");
      def age = obj.getIntValue("age");
      // You can log in the app server output to check your code
      // System.out.println("Age: " + age);
      // System.out.println("First name: " + first_name);
      // System.out.println("Last name: " + last_name);
   
      if (first_name.equals(last_name)) {
        // You can log in the app server output to check your code
        // System.out.println("firstname");
        // This stores the validation error message. The translation string is "val_firstname_lastname"
        XWikiValidationStatus.addErrorToContext("ValidationSample.ValidationSampleClass", "", "", "val_firstname_lastname", context); 
        res = false;
      }
      if (age<20 || age>24) {
        // You can log in the app server output to check your code
        // System.out.println("age");
        // This stores the validation error message. The translation string is "val_age_incorrect"
        XWikiValidationStatus.addErrorToContext("ValidationSample.ValidationSampleClass", "age", "Age", "val_age_incorrect", context); 
        res = false;
      }
      return res;
    }
    public boolean validateObject(BaseObject object, XWikiContext context) { 
      return true;
    }
}

How to display validation error messages

Display all validation error message at the top of the document

The following macro can be used:

### this macro shows all the errors
#macro(showallerrors)
#if(($context.validationStatus.errors&&$context.validationStatus.errors.size()>0)||($context.validationStatus.exceptions&&$context.validationStatus.exceptions.size>0))
<div class="validation-errors" style="border: 1px solid grey; padding: 10px;">
This is a recap of all errors in this page (change the form to show errors only at the top or only next to the fields):

#foreach($error in $context.validationStatus.errors)
<font color="red">$xwiki.parseMessage($error)</font><br />
#end

#foreach($exp in $context.validationStatus.exceptions)
<font color="red">$exp</font><br />
#end
</div>
#end
#end  ## end showallerrors macro

This is called using

#showallerrors()

Display the validation error messages next to the field

The following macro can be used to show the validation error called $message

### this macro shows a validation error message if it exists
#macro(showvalidationmessage $message)
#if($context.validationStatus.errors.contains($message))
<font color="red">$xwiki.parseMessage($message)</font><br />
#end
#end ## end showvalidationmessage

This is called using

#showvalidationmessage("val_firstname_toolong")

How to create tooltips, mandatory icon and the pretty name

The following macro shows a field including the mandatory field, the tooltip and the pretty name

#macro(showfield $fieldname $mandatory)
#if($mandatory&&!$mode.equals("view"))
#set($mand = true)
#else
#set($mand = false)
#end
## displayPrettyName will get the translation only with patch in http://jira.xwiki.org/jira/browse/XWIKI-2383
<dt>$valdoc.displayPrettyName($fieldname, $mand): #if($context.action=="inline")$valdoc.displayTooltip($fieldname)#end</dt>
<dd>
$valdoc.display($fieldname, $mode)
</dd>
#end ## end showfield macro

This is called using:

#showfield("first_name",true)

In addition the following code needs to be called at the end of the page:

## this is necessary for the tooltips to work
$xwiki.addTooltipJS()

The tooltip

$valdoc.displayTooltip("first_name")

The pretty name with mandatory icon

$valdoc.displayPrettyName("first_name", true)

The pretty name without mandatory icon

$valdoc.displayPrettyName("first_name")
$valdoc.displayPrettyName("first_name", false)

How to validate and save the document in CreateDoc

#set($docname = $xwiki.getUniquePageName("ValidationSample", "Val"))
#set($valdoc = $xwiki.getDocument("ValidationSample.${docname}"))
#set($ok = $valdoc.setContent($xwiki.getDocument("ValidationSample.ValidationSampleClassTemplate").getContent()))
#set($ok = $valdoc.setParent("ValidationSample.WebHome"))
#set($ok = $valdoc.newObject("ValidationSample.ValidationSampleClass"))
#set($ok = $valdoc.updateObjectFromRequest("ValidationSample.ValidationSampleClass"))
## this does not work yet because of bug http://jira.xwiki.org/jira/browse/XWIKI-2382
## the validation script needs to be passed in the request
#set($ok = $valdoc.setValidationScript("ValidationSample.ValidationGroovy"))
#if($valdoc.validate()==true)
Ok it's good to save. 
$valdoc.save()
You can access your new document [here>$docname].
#else
<form action="CreateDoc" method="post">
#set($mode="edit")
#includeInContext("ValidationSample.ValidationSampleClassSheet")
<input type="submit" value="Create" />
</form>
#end

Complete presentation sheet of the document

### setting right mode for the sheet 
### setting $valdoc variable either already set or set to $doc
#if(!$mode)
#if($context.action=="inline")
#set($mode = "edit") 
#else
#set($mode = "view") 
#end
#end
#if(!$valdoc)
#set($valdoc = $doc)
#end
## Force validation
<input type="hidden" name="xvalidate" value="1" />
## Set the validation script. This is necessary until the bug http://jira.xwiki.org/jira/browse/XWIKI-2382
<input type="hidden" name="xvalidation" value="ValidationSample.ValidationGroovy" />

#### begin display macros
### this macro shows a validation error message if it exists
#macro(showvalidationmessage $message)
#if($context.validationStatus.errors.contains($message))
<font color="red">$xwiki.parseMessage($message)</font><br />
#end
#end ## end showvalidationmessage
### this macros displays a field and it's tooltip
#macro(showfield $fieldname $mandatory)
#if($mandatory&&!$mode.equals("view"))
#set($mand = true)
#else
#set($mand = false)
#end
## displayPrettyName will get the translation only with patch in http://jira.xwiki.org/jira/browse/XWIKI-2383
<dt>$valdoc.displayPrettyName($fieldname, $mand): #if($context.action=="inline")$valdoc.displayTooltip($fieldname)#end</dt>
<dd>
$valdoc.display($fieldname, $mode)
</dd>
#end ## end showfield macro
### this macro shows all the errors
#macro(showallerrors)
#if(($context.validationStatus.errors&&$context.validationStatus.errors.size()>0)||($context.validationStatus.exceptions&&$context.validationStatus.exceptions.size>0))
<div class="validation-errors" style="border: 1px solid grey; padding: 10px;">
This is a recap of all errors in this page (change the form to show errors only at the top or only next to the fields):

#foreach($error in $context.validationStatus.errors)
<font color="red">$xwiki.parseMessage($error)</font><br />
#end

#foreach($exp in $context.validationStatus.exceptions)
<font color="red">$exp</font><br />
#end
</div>
#end
#end  ## end showallerrors macro
##### end macros

$valdoc.use("ValidationSample.ValidationSampleClass")
#showallerrors()
#showvalidationmessage("val_firstname_toolong")
#showvalidationmessage("val_firstname_lastname")
#showfield("first_name",true)
#showvalidationmessage("val_lastname_toolong")
#showfield("last_name",true)
#showvalidationmessage("val_age_incorrect")
#showfield("age",true)
#showvalidationmessage("val_email_shouldbedotcom")
#showfield("email",true)
#showvalidationmessage("val_usphone_incorrectformat")
#showfield("usphone",true)
#showvalidationmessage("val_text_toolong")
#showfield("text",false)

## this is necessary for the tooltips to work
$xwiki.addTooltipJS()
Version 7.3 last modified by Sergiu on 19/05/2008 at 18:08

Comments 0

No comments for this document

Attachments 3

BIN
validation-sample-1.0.xar 1.1
PostedBy: LudovicDubost on 18/05/2008 (384kb )
Image
formvalidationedit.png 1.1
PostedBy: LudovicDubost on 18/05/2008 (66kb )
Image
formvalidationclass.png 1.1
PostedBy: LudovicDubost on 18/05/2008 (359kb )

Creator: LudovicDubost on 2008/05/18 03:21
This wiki is licensed under a Creative Commons license
1.4.1.10194