shale-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Apache Wiki <wikidi...@apache.org>
Subject [Shale Wiki] Update of "ShaleValidation" by ReneZanner
Date Mon, 31 Jul 2006 10:04:15 GMT
Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Shale Wiki" for change notification.

The following page has been changed by ReneZanner:
http://wiki.apache.org/shale/ShaleValidation

The comment on the change is:
content moved from Struts wiki

New page:
##language:en
#pragma section-numbers off
||<rowbgcolor="#FFFFE0">[http://struts.apache.org/struts-shale/index.html Shale Home]||[:Shale:Wiki
Home]||[:Shale/UserDocs:User Docs]||[:Shale/SiteMap:Index]||[:Shale/WikiGuidelines:Guidelines]||[:../:Go
Up]||
-----

== Shale Commons Validator Integration ==

 * http://struts.apache.org/struts-shale/features-commons-validator

=== Validation error messages and the <s:validatorVar> tag ===

The parameters used to format the [http://svn.apache.org/repos/asf/struts/shale/trunk/core-library/src/java/org/apache/shale/validator/messages.properties
error messages] that are shown when a validation error occurs include the incorrect value
and any validator-specific 'var' parameters.

When the <s:validatorVar> tag is used for validator-specific 'var' parameters, the order
in which the 'var's are declared is the order that will be used to format the error message.

For a 'range' validator, such as 'floatRange', the error message pattern is:

{{{errors.range={0} is not in the range {1} through {2}.}}}

Therefore, when using a "range" validator with the <s:validatorVar> tags, specify the
"min" var before the "max" var:

{{{
<s:commonsValidator type="floatRange"
                     arg="#{msgs.amount}"
                  server="true"
                  client="false">
    <s:validatorVar name="min" value="10"/>
    <s:validatorVar name="max" value="1000"/>
</s:commonsValidator>
}}}


=== Using Custom Validation Rules with Shale ===

To use a custom validation rule in your application, complete the following steps:

'''1. Define an xml file conforming to the Commons Validator 1.2.0 dtd.'''

In this example, the file will be named 'custom-rules.xml' and will be placed in /WEB-INF.

{{{
<!DOCTYPE form-validation PUBLIC
          "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN"
          "http://jakarta.apache.org/commons/dtds/validator_1_2_0.dtd">
<form-validation>
   <global>
       <validator name="evenNumber"
             classname="com.example.ValidationUtil"
             method="isEven"
             methodParams="int"
             msg="errors.even">
       </validator>
   </global>
</form-validation>
}}}

'''2. Write the validation method.'''

{{{
package com.example;
public class ValidationUtil implements Serializable
{
    public static boolean isEven( int value ) {
       return (value % 2 == 0);
    }
}
}}}

'''3. Configure the validation rules in web.xml.'''

Include the default rule set by listing "/org/apache/shale/validator/validator-rules.xml"
in addition to your custom rules.

{{{
    <!-- Shale Validator Configuration Resources -->
    <context-param>
       <param-name>org.apache.shale.validator.VALIDATOR_RULES</param-name>
       <param-value>
           /org/apache/shale/validator/validator-rules.xml,
           /WEB-INF/custom-rules.xml
       </param-value>
    </context-param>
}}}

!CommonsValidator will pass the value entered by the user as the first parameter of your validation
method, provided you have listed at least one type in the 'methodParams' attribute of your
<validator> tag.

In addition, if you add them as attributes to the <s:commonsValidator> tag, !CommonsValidator
will pass the following parameters through to your validation method:  min, max, minlength,
maxlength, mask, and datePatternStrict.  These parameters are always passed in exactly this
order, no matter how they are listed in <s:commonsValidator>.

'''4. Provide a resource bundle for messages.''' (Optional)

The !CommonsValidator class reads the messages from the application's resource bundle, then
from the 'messages' bundle in org.apache.struts.validator (the (localized) messages.properties
file inside shale-core.jar).

If you can use one of the provided messages for your validator, then no action is necessary.

If you need to provide additional messages or override any of the provided messages, here's
how:

Configure a resource bundle for your application in faces-config.xml.  For example:

{{{
    <application>
        <message-bundle>ApplicationResources</message-bundle>
        <locale-config>
            <default-locale>en</default-locale>
            <supported-locale>en</supported-locale>
        </locale-config>
    </application>
}}}

And add your message to it. In this example, the file would be '/WEB-INF/classes/!ApplicationResources.properties'.

{{{
     errors.even={0} is not an even number.
}}}

The value of the field being validated is automatically passed as {0} for message parameter
replacement.

'''5. Attach your new validation rule to a component.'''

In this example, we have a text field called "Priority" which will only accept an even number.

{{{
    <h:outputText value="#{messages['prompt.priority']}"/>
    <h:inputText     id="priority"
                  value="#{priority}">
          <s:commonsValidator
                   type="evenNumber"
                 server="true"
                 client="false"/>
    </h:inputText>
     <h:message           for="priority" styleClass="errors"/>
}}}

'''6. Reminders'''

Be sure to add the <s:validatorScript> at the end of your form, and to set the the 'onsubmit'
attribute of the <h:form> tag.

{{{
  <h:form onsubmit="return validateForm(this);">
     ...
     <s:validatorScript functionName="validateForm"/>
  </h:form>
}}}

'''ATTENTION:''' When using commandButton with immediate="true" for wizard-style "back" navigation,
be sure to remove the "onsubmit" handler from the form and attach it to the normal "next"
commandButton ("onclick" handler) instead. Otherwise the client-side validation will be executed
even in the "back" navigation case.

{{{
  <h:form>
     ...
     <h:commandButton action="back" immediate="true" ... />
     <h:commandButton action="#{wizard.gotoPage2}" onclick="return validateForm(this.form);"
... />
     <s:validatorScript functionName="validateForm"/>
  </h:form>
}}}

=== Using Rules With Multiple Parameters ===

The following example demonstrates the use of all of the attributes accepted by the <s:commonsValidator>
tag, though it's unlikely that a single validator would make use of all six method parameters:
 min, max, minlength, maxlength, mask and datePatternStrict.

Numbered as above:

'''1.'''
{{{
       <validator name="allParams"
             classname="com.example.ValidationUtil"
             method="isValid"
             methodParams="java.lang.String,double,double,int,int,java.lang.String,java.lang.String"
             msg="errors.all">
       </validator>
}}}

'''2.'''
{{{
    public static boolean isValid( String value, double min, double max, int minlength, int
maxlength,
                                   String mask, String datePatternStrict) {
        return false;
    }
}}}

The attributes will be passed as parameters to your validation method in exactly this order,
though most validators will only use a subset of the available attributes.

'''4.'''
{{{
errors.all={0} must be at least {1}, not more than {2}, between {3} and {4} in length, and
conform to mask {5} and date pattern {6}.  Good luck!
}}}

'''5.'''
{{{
            <s:commonsValidator
                     type="allParams"
                   server="true"
                   client="false"
                      max="5.7"
                minlength="2"
                      min="1.2"
                maxlength="6"
                     mask="[4-6].*"
        datePatternStrict="MM/dd/yyyy" />
}}}

Note that this will ''always'' fail because the 'isValid' method returns false.

=== Required Validator ===

The 'required' validator is a special case.  The JSF framework will only call a Validator
if a value was submitted.  Usually, you would set required="true" as an attribute on the input
component.

So that you don't have to remember to do something different for 'required', Shale allows
<s:validator type="required">, which works by setting the required attribute of the
surrounding input component to true.

The 'required' validator is defined in validator-rules.xml as:
{{{
      <validator name="required"
            classname="org.apache.shale.validator.CommonsValidator"
               method="isSupplied"
         methodParams="java.lang.String"
                  msg="errors.required">
         <javascript>...</javascript>
      </validator>
}}}

However, neither the 'isSupplied' method in !CommonsValidator, nor the 'errors.required' message
is ever used.

To override the message that is displayed when a required field is missing, add an entry for
"javax.faces.component.UIInput.REQUIRED" to your application's message bundle.

=== References ===

 * http://struts.apache.org/struts-shale/features-commons-validator.html
  * [http://struts.apache.org/struts-shale/shale-core/apidocs/org/apache/shale/validator/CommonsValidator.html
CommonsValidator API]
  * [http://struts.apache.org/struts-shale/shale-core/apidocs/org/apache/shale/component/ValidatorScript.html
ValidatorScript API]

 * http://jakarta.apache.org/commons/validator/
  * [http://jakarta.apache.org/commons/validator/api-1.2.0/org/apache/commons/validator/ValidatorResources.html
ValidatorResources API]
  * [http://jakarta.apache.org/commons/validator/api-1.2.0/org/apache/commons/validator/GenericValidator.html
GenericValidator API]

 * David and Mike explaining about the 'required' validator on [http://marc.theaimsgroup.com/?l=struts-dev&m=113624114424542&w=2
MARC] or [http://www.mail-archive.com/dev%40struts.apache.org/msg16825.html mail-archive].

-----

=== Enhancements ===

 * [http://issues.apache.org/bugzilla/show_bug.cgi?id=38042 Bug 38042] - The default validator-rules.xml
file is included in shale-core.jar (Since 1.0.1).

 * [http://issues.apache.org/bugzilla/show_bug.cgi?id=38044 Bug 38044] - The filename and
location of validator rules files are configurable (Since 1.0.1).

-----
''Please address questions about Shale's Commons Validator integration to the [http://struts.apache.org/mail.html
struts-user] list.'''

Mime
View raw message