XWiki Platform » Documentation for the XWiki Platform » Developer's Guide » Tutorials » Creating a form with validation and tooltips

Creating a form with validation and tooltips

Last modified by Silvia Rusu on 2012/03/20 13:29

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 up to XWiki 1.5 M2:

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. If the field can have new lines, enable the dotall mode (http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#DOTALL) by adding an s at the end of the regex (/^.{2,20}$/s) otherwise a regex that contains a new line will not pass validation.
    • 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

Other Validation Regular Expression examples:

  • do not match XWiki.XWikiGuest, but allow it to be inside the string: /^(?!XWiki.XWikiGuest$).*/
  • forbit XWiki.XWikiGuest anywhere in the string: /^(?!.*XWiki.XWikiGuest).*/

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 not needed after XE 1.5 M2 http://jira.xwiki.org/jira/browse/XWIKI-2382
<input type="hidden" name="xvalidation" value="ValidationSample.ValidationGroovy" />

Here is the sample groovy script:

Do not use the {{groovy}} macro when creating your script, just paste your code in the wiki editor.
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()

Client side validation with LiveValidation

It's important to have server side validation for security and because not everyone uses Javascript but client side validation
while the user types can improve the user's experience and save server load from forms submitted over and over again.
To do validation on the client side you have to use the LiveValidation Javascript code. You can define your own style for
validation error messages or you can use the style sheet which is used by XWiki.Registration.

Here is a simple example of how to use LiveValidation in XWiki:

{{velocity}}
$xwiki.get('jsfx').use('uicomponents/widgets/validation/livevalidation_prototype.js')
$xwiki.get('ssfx').use('uicomponents/widgets/validation/livevalidation.css')
{{/velocity}}
{{html}}
<form action="">
<label for="helloField">Say hello to LiveValidation:</label>
<input id="helloField" length="20" type="text">
</form>
<script>
/* <![CDATA[ */
document.observe('dom:loaded', function() {
var helloField = new LiveValidation("helloField", { validMessage: "Hi There.", wait: 500} );
helloField.add( Validate.Presence, { failureMessage: "Say Something, anything..."} );
helloField.add( Validate.Format, { pattern: /^[Hh]ello$/, failureMessage: "How about saying 'Hello'?"} );
});// ]]>

</script>
{{/html}}

The result is this:

This example shows validation of presence (something must be written) and validation of format (testing against a regular expression).
Notice how the first line of Javascript says 'new LiveValidation("helloField"' this binds the validation to field with the id "helloField". Text validation also works on TextAreas.
There are more types of validation which are documented in the LiveValidation documentation.
To change the look and feel of the error message, you may define your own CSS skin extension instead of using the one provided.
All validation messages are of the class LV_validation_message The error messages are of the class LV_invalid and the valid messages are of class LV_valid. LiveValidation will also detect submit buttons and bind to them, blocking them if fields are invalid. There are ways around this such as using propotype's Event.stopObserving function.

Tags:
Created by Ludovic Dubost on 2008/05/18 03:21