The Validator Framework The Validator Framework Chuck Cavaness - - PowerPoint PPT Presentation
The Validator Framework The Validator Framework Chuck Cavaness - - PowerPoint PPT Presentation
The Validator Framework The Validator Framework Chuck Cavaness Chuck Cavaness Chuck Cavaness Introduction Introduction Senior Technologist (S1 Corporation) Senior Technologist (S1 Corporation) Co Co- -Author of Special
Introduction Introduction
- Senior Technologist (S1 Corporation)
Senior Technologist (S1 Corporation)
- Co
Co-
- Author of Special Edition EJB 2.0 and Special
Author of Special Edition EJB 2.0 and Special Edition Java 2 Edition Java 2
- Author of Jakarta Struts from O’Reilly and Struts
Author of Jakarta Struts from O’Reilly and Struts Pocket Reference Pocket Reference
- Various Articles for O’Reilly, Linux Magazine,
Various Articles for O’Reilly, Linux Magazine, JavaWorld, etc. JavaWorld, etc.
Agenda Agenda
- The Need for Validation
The Need for Validation
- Basic Validation Concepts
Basic Validation Concepts
- Introduce the Validator Framework
Introduce the Validator Framework
- Validator with/without Struts
Validator with/without Struts
- Discuss Validator Best Practices
Discuss Validator Best Practices
What’s the Big Deal? What’s the Big Deal?
! ! Lexical Validation
Lexical Validation
! ! Syntactic Validation
Syntactic Validation
! ! Semantic Validation
Semantic Validation
Lexical Validation Lexical Validation
- Is the single value “well
Is the single value “well-
- formed”?
formed”?
- The Structure of the data is correct
The Structure of the data is correct
- But nothing can be said of the content
But nothing can be said of the content
- Can typically be done on the client or server
Can typically be done on the client or server
- E.g. Did the user enter an integer for an age
E.g. Did the user enter an integer for an age field? field?
Syntactic Validation Syntactic Validation
- Well
Well-
- formed, but does the data follow
formed, but does the data follow the proper syntax the proper syntax
- Can typically be done on client, but must
Can typically be done on client, but must watch out for I18N issues watch out for I18N issues
- E.g < day> /< month> /< year>
E.g < day> /< month> /< year>
Semantic Validation Semantic Validation
- Does the data make sense for your
Does the data make sense for your domain domain
- Should be done on server
Should be done on server
- E.g. You asked for a future ship date, but
E.g. You asked for a future ship date, but the user entered a date in the past the user entered a date in the past
The Need for Validation The Need for Validation
Enterprise Data
J2 EE Cluster
W AP Server Web Server/ Servlet Container Cluster AS4 0 0 Business Partners SOAP/ XML Web Services JDBC RMI/ IIOP RMI/ IIOP Internal Applications JDBC Native Batch
Where does the Validation Where does the Validation Live? Live?
- Business Logic Validation
Business Logic Validation
- Presentation Validation
Presentation Validation
Presentation vs. Business Logic Presentation vs. Business Logic
Enterprise Data Web Server/ Servlet Container J2 EE Server HttpRequest HttpResponse HttpRequest EJB I nvocation SQL Query
Authenticate( )
Validation without the Validation without the Validator Validator
- public ActionErrors validate(ActionMapping mapping, HttpServlet
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { Request request) {
- ActionErrors errors = new ActionErrors();
ActionErrors errors = new ActionErrors();
- / / Get access to the message resources for this application
/ / Get access to the message resources for this application
- / / There's not an easy way to access the resources from an A
/ / There's not an easy way to access the resources from an ActionForm ctionForm
- MessageResources resources =
MessageResources resources =
- (MessageResources)request.getAttribute( Globals.MESSAGES_K
(MessageResources)request.getAttribute( Globals.MESSAGES_KEY ); EY );
- / / Validate that the usernam e entered was not null
/ / Validate that the usernam e entered was not null
- if(getUsernam e() = = null | | getUsernam e().length() < 1) {
if(getUsernam e() = = null | | getUsernam e().length() < 1) {
- String usernam eLabel = resources.getMessage( "label.usernam e
String usernam eLabel = resources.getMessage( "label.usernam e" ); " );
- errors.add( ActionErrors.GLOBAL_ERROR,
errors.add( ActionErrors.GLOBAL_ERROR,
- new ActionError("errors.required", usernam eLab
new ActionError("errors.required", usernam eLabel )); el ));
- }
}
- / / Validate that the password entered was not null
/ / Validate that the password entered was not null
- if(getPassword() = = null | | getPassword().length() < 1) {
if(getPassword() = = null | | getPassword().length() < 1) {
- String passwordLabel = resources.getMessage( "label.password
String passwordLabel = resources.getMessage( "label.password" ); " );
- errors.add( ActionErrors.GLOBAL_ERROR,
errors.add( ActionErrors.GLOBAL_ERROR,
- new ActionError("errors.required", passwordLab
new ActionError("errors.required", passwordLabel )); el ));
- }
}
- return errors;
return errors;
- }
}
Order Form Order Form Order Form
Extrapolating this Approach to Validating Extrapolating this Approach to Validating
Username and Password Account Number, Email, Contact Information, etc. Credit Card, Quantity, Shipping Address, etc. Logon Form Logon Form Order Form Order Form Order Form Customer Form
The Validator Framework The Validator Framework
- Open source Validation framework
Open source Validation framework
- Developed by David Winterfeldt
Developed by David Winterfeldt
- Integrated into Struts core during 1.1
Integrated into Struts core during 1.1
Features of the Validator Features of the Validator
- Supports Client
Supports Client-
- Side (JavaScript) and Server
Side (JavaScript) and Server-
- Side (Java) validation
Side (Java) validation
- Comes with many pre
Comes with many pre-
- built validation routines
built validation routines
- Allows for regular expressions to be used
Allows for regular expressions to be used
- Can be used with or without Struts
Can be used with or without Struts
- Pluggable Validators
Pluggable Validators
Validator Rules Repository Application Validator Mappings
Validator Framework
Architecture of the Validator Architecture of the Validator
Struts Framework Application Framework
Action Form s Request Processor Actions Validators Plugin Validator Action Form s
Validator Sequence Diagram Validator Sequence Diagram
Login Form ActionServlet doPost RequestProcessor {login.do was sent in request} process() processValidate() ActionForm validate() Validator validate()
Basic Validation Rules Basic Validation Rules
- Required
Required
- Mask
Mask
- Range(
Range(intRange,
intRange, floatRange floatRange)
)
- MaxLength
MaxLength
- MinLength
MinLength
- Date
Date
- Credit Card
Credit Card
- Byte,short,Integer
Byte,short,Integer
- Long,Double,Float
Long,Double,Float
Using the Validator with Using the Validator with Struts Struts
1.
- 1. Add the Validator Plugin
Add the Validator Plugin 2.
- 2. Configure the Validation.xml File
Configure the Validation.xml File 3.
- 3. Extend the Validator ActionForms or use
Extend the Validator ActionForms or use Dynamic ActionForms Dynamic ActionForms 4.
- 4. Set validate= “true” on Action Mappings
Set validate= “true” on Action Mappings
Adding Validator Plugin Adding Validator Plugin
<plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in>
Validator Configuration Files Validator Configuration Files
- validator
validator-
- rules.xml
rules.xml
- validation.xml
validation.xml
The Rules Configuration File The Rules Configuration File
<validator name="required" classname="org.apache.struts.util.StrutsValidator" method="validateRequired" methodParams="java.lang.Object,
- rg.apache.commons.validator.ValidatorAction,
- rg.apache.commons.validator.Field,
- rg.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest" msg="errors.required"> //…some text deleted
Validation Configuration File Validation Configuration File
… < form name= “loginForm "> < field property= “em ail" depends= "required"> < arg0 key= “label.em ail"/ > < / field> < field property= “passw ord" depends= "required"> < arg0 key= “label.passw ord"/ > < / field> < / form> …
Resource Bundle Resource Bundle
… errors.required= { 0 } is required. errors.minlength= { 0} can not be less than { 1} characters. errors.maxlength= { 0} can not be greater than { 1} characters. errors.invalid= { 0} is invalid. errors.byte= { 0} must be an byte. errors.short= { 0} must be an short. errors.integer= { 0} must be an integer. errors.long= { 0} must be an long. errors.float= { 0} must be an float. errors.double= { 0} must be an double. errors.date= { 0} is not a date. …
ActionForms and the Validator ActionForms and the Validator
- Standard ActionForms
Standard ActionForms
– – ValidatorActionForm ValidatorActionForm – – ValidatorForm ValidatorForm
- Dynamic ActionForms
Dynamic ActionForms
– – DynaValidatorActionForm DynaValidatorActionForm – – DynaValidatorForm DynaValidatorForm
Validator supports both types of ActionForms:
ActionForm Hierarchy ActionForm Hierarchy
A Validator Example! A Validator Example!
Let’s step through an example.
Using JavaScript with the Validator Using JavaScript with the Validator
< javascript> < ![ CDATA[ function validateMinLength(form) { var isValid = true; var focusField = null; var i = 0; var fields = new Array();
- MinLength = new minlength();
for (x in oMinLength) { var field = form[ oMinLength[ x] [ 0] ] ; if (field.type = = 'text' | | field.type = = 'textarea') { var iMin = parseI nt(oMinLength[ x] [ 2] ("minlength")); if ((field.value.length > 0) && (field.value.length < iMin)) { if (i = = 0) { focusField = field; } fields[ i+ + ] = oMinLength[ x] [ 1] ; isValid = false; } } } if (fields.length > 0) { focusField.focus(); alert(fields.join('\ n')); } return isValid; } ] ] > < / javascript>
Using JavaScript with the Validator Using JavaScript with the Validator
I18N and the Validator I18N and the Validator
- Validator framework uses the Struts
Validator framework uses the Struts resource bundle resource bundle
- The < formset> element supports
The < formset> element supports language, country and variant language, country and variant
< formset> … < / formset> < formset language= "fr"> … < / formset> < formset language= "fr" country= "CA"> … < / formset>
Validator Advanced Topics Validator Advanced Topics
- Creating Custom Validators
Creating Custom Validators
- Using Programmatic Validation along with
Using Programmatic Validation along with the Validator the Validator
- Validating Dependent Fields
Validating Dependent Fields
- Using the Validator outside of Struts
Using the Validator outside of Struts
Creating Custom Validation Creating Custom Validation Rules Rules
1.
- 1. Create the new validation method.
Create the new validation method. 2.
- 2. Modify the validation
Modify the validation-
- rules.xml file to
rules.xml file to contain the new validation method. contain the new validation method. 3.
- 3. Modify the validation.xml file to use the
Modify the validation.xml file to use the new validation rule. new validation rule.
Creating the Custom Method Creating the Custom Method
public static boolean validateExactLength(Object bean, ValidatorAction va, Field field, ActionErrors errors, HttpServletRequest request) { String value = null; if (isString(bean)) { value = (String) bean; } else { value = ValidatorUtil.getValueAsString(bean, field.getProperty()); } String exactLength = field.getVarValue("exactlength"); if (!GenericValidator.isBlankOrNull(value)) { try { int length = Integer.parseInt(exactLength); if ( value.length() != length ) { errors.add(field.getKey(), Resources.getActionError(request, va, field)); return false; } } catch (Exception e) { errors.add(field.getKey(), Resources.getActionError(request, va, field)); return false; } } return true; }
Updating validator Updating validator-
- rules.xml
rules.xml
< validator name= "exactLength" classname= "MyValidator" method= "validateExactLength" methodParams= "java.lang.Object,
- rg.apache.commons.validator.ValidatorAction,
- rg.apache.commons.validator.Field,
- rg.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest“ depends= “required” m sg= "errors.exactlength"> < / validator>
Declaring the New Rule Declaring the New Rule
… < form name= "checkoutForm"> < field property= "shippingAddress" depends= "exactLength"> < arg0 key= "label.address"/ > < arg1 name= "exactLength" key= "$ { var:exactlength} " resource= "false"/ > < var> < var-nam e> exactlength< / var-nam e> < var-value> 1 0 < / var-value> < / var> < / field> < field property= "shippingCity" depends= "required,mask"> < arg0 key= "label.city"/ > < var> < var-name> mask< / var-name> < var-value> ^ [ a-zA-Z] * $< / var-value> < / var> < / field> …
Executing the Executing the ExactLength ExactLength Rule Rule
Using Programmatic and Declarative Using Programmatic and Declarative Validator Validator
It’s possible to use manual validation along It’s possible to use manual validation along with the Validator framework. with the Validator framework.
public class LoginForm extends ValidatorActionForm { public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { / / Call the super validate so the Validator framework can do its thing! ActionErrors errors = super.validate( mapping, request ); / / Do some special customized validation stuff here / / In the end, return any and all ActionErrors return errors; } }
Validating Dependent Fields Validating Dependent Fields
- Currently done using the
Currently done using the RequiredIf RequiredIf Rule Rule
- In a future release (after 1.1 GA), the
In a future release (after 1.1 GA), the validwhen validwhen Rule should be used. Rule should be used.
Using the Validator outside of Using the Validator outside of Struts Struts
- Can be used to provide validation on any
Can be used to provide validation on any JavaBean JavaBean
- Package Dependencies include:
Package Dependencies include:
– – ORO ORO – – Commons Logging, Commons Logging, BeanUtils BeanUtils, Collections, , Collections, Digester Digester – – XML Parser XML Parser
Using the Validator outside of Using the Validator outside of Struts (cont) Struts (cont)
- Some upfront work is necessary
Some upfront work is necessary
- Method signatures must be changed in
Method signatures must be changed in validation validation-
- rules.xml
rules.xml
- The same validation.xml file can be used
The same validation.xml file can be used
Resources Resources
- Validator Home
Validator Home -
- http://
http:// jakarta jakarta.apache.org/commons/validator/index.html .apache.org/commons/validator/index.html
- An O’Reilly Article by Chuck Cavaness
An O’Reilly Article by Chuck Cavaness -
- http://www.onjava.com/pub/a/onjava/2002/12/11/jakartastruts.html
http://www.onjava.com/pub/a/onjava/2002/12/11/jakartastruts.html
- Home of the Validator Creator
Home of the Validator Creator – – http://home.earthlink.net/~ http://home.earthlink.net/~ dwinterfeldt dwinterfeldt
- Struts User Guide Info
Struts User Guide Info -
- http://
http:// jakarta jakarta.apache.org/struts/ .apache.org/struts/ userGuide userGuide/dev_validator.html /dev_validator.html
- Browsing the Struts List
Browsing the Struts List -
- http://marc.theaimsgroup.com
http://marc.theaimsgroup.com or
- r
http:// http:// nagoya nagoya.apache.org/ .apache.org/ eyebrowse eyebrowse