2
* $Header: /home/cvs/jakarta-commons/validator/src/example/org/apache/commons/validator/example/ValidateExample.java,v 1.17 2004/02/21 17:10:29 rleland Exp $
4
* $Date: 2004/02/21 17:10:29 $
6
* ====================================================================
7
* Copyright 2000-2004 The Apache Software Foundation
9
* Licensed under the Apache License, Version 2.0 (the "License");
10
* you may not use this file except in compliance with the License.
11
* You may obtain a copy of the License at
13
* http://www.apache.org/licenses/LICENSE-2.0
15
* Unless required by applicable law or agreed to in writing, software
16
* distributed under the License is distributed on an "AS IS" BASIS,
17
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
* See the License for the specific language governing permissions and
19
* limitations under the License.
22
package org.apache.commons.validator.example;
24
import java.io.IOException;
25
import java.io.InputStream;
26
import java.text.MessageFormat;
27
import java.util.Iterator;
28
import java.util.Locale;
30
import java.util.ResourceBundle;
32
import org.apache.commons.validator.Field;
33
import org.apache.commons.validator.Form;
34
import org.apache.commons.validator.Validator;
35
import org.apache.commons.validator.ValidatorAction;
36
import org.apache.commons.validator.ValidatorException;
37
import org.apache.commons.validator.ValidatorResources;
38
import org.apache.commons.validator.ValidatorResult;
39
import org.apache.commons.validator.ValidatorResults;
40
import org.xml.sax.SAXException;
43
* <p>A simple example of setting up and using the Validator.</p>
45
* This simple example shows all the steps needed to set up and use
46
* the Validator. Note that in most cases, some kind of framework
47
* would be wrapped around the Validator, such as is the case with
48
* the Struts Validator Framework. However, should you wish to use
49
* the Validator against raw Beans in a pure Java application, you
50
* can see everything you need to know to get it working here.
52
public class ValidateExample extends Object {
55
* We need a resource bundle to get our field names and errors messages
56
* from. Note that this is not strictly required to make the Validator
57
* work, but is a good coding practice.
59
private static ResourceBundle apps =
60
ResourceBundle.getBundle(
61
"org.apache.commons.validator.example.applicationResources");
64
* This is the main method that will be called to initialize the Validator, create some sample beans, and
65
* run the Validator against them.
67
public static void main(String[] args)
68
throws ValidatorException, IOException, SAXException {
70
InputStream in = null;
71
ValidatorResources resources = null;
75
// Create a new instance of a ValidatorResource, then get a stream
76
// handle on the XML file with the actions in it, and initialize the
77
// resources from it. This would normally be done by a servlet
78
// run during JSP initialization or some other application-startup
80
in = ValidateExample.class.getResourceAsStream("validator-example.xml");
81
resources = new ValidatorResources(in);
84
// Make sure we close the input stream.
90
// Create a test bean to validate against.
91
ValidateBean bean = new ValidateBean();
93
// Create a validator with the ValidateBean actions for the bean
94
// we're interested in.
95
Validator validator = new Validator(resources, "ValidateBean");
97
// Tell the validator which bean to validate against.
98
validator.setParameter(Validator.BEAN_PARAM, bean);
100
ValidatorResults results = null;
102
// Run the validation actions against the bean. Since all of the properties
103
// are null, we expect them all to error out except for street2, which has
104
// no validations (it's an optional property)
106
results = validator.validate();
107
printResults(bean, results, resources);
109
// Now set all the required properties, but make the age a non-integer.
110
// You'll notice that age will pass the required test, but fail the int
112
bean.setLastName("Tester");
113
bean.setFirstName("John");
114
bean.setStreet1("1 Test Street");
115
bean.setCity("Testville");
117
bean.setPostalCode("12345");
118
bean.setAge("Too Old");
119
results = validator.validate();
120
printResults(bean, results, resources);
122
// Now only report failed fields
123
validator.setOnlyReturnErrors(true);
124
results = validator.validate();
125
printResults(bean, results, resources);
127
// Now everything should pass.
128
validator.setOnlyReturnErrors(false);
130
results = validator.validate();
131
printResults(bean, results, resources);
135
* Dumps out the Bean in question and the results of validating it.
137
public static void printResults(
139
ValidatorResults results,
140
ValidatorResources resources) {
142
boolean success = true;
144
// Start by getting the form for the current locale and Bean.
145
Form form = resources.getForm(Locale.getDefault(), "ValidateBean");
147
System.out.println("\n\nValidating:");
148
System.out.println(bean);
150
// Iterate over each of the properties of the Bean which had messages.
151
Iterator propertyNames = results.getPropertyNames().iterator();
152
while (propertyNames.hasNext()) {
153
String propertyName = (String) propertyNames.next();
155
// Get the Field associated with that property in the Form
156
Field field = form.getField(propertyName);
158
// Look up the formatted name of the field from the Field arg0
159
String prettyFieldName = apps.getString(field.getArg(0).getKey());
161
// Get the result of validating the property.
162
ValidatorResult result = results.getValidatorResult(propertyName);
164
// Get all the actions run against the property, and iterate over their names.
165
Map actionMap = result.getActionMap();
166
Iterator keys = actionMap.keySet().iterator();
167
while (keys.hasNext()) {
168
String actName = (String) keys.next();
170
// Get the Action for that name.
171
ValidatorAction action = resources.getValidatorAction(actName);
173
// If the result is valid, print PASSED, otherwise print FAILED
179
+ (result.isValid(actName) ? "PASSED" : "FAILED")
182
//If the result failed, format the Action's message against the formatted field name
183
if (!result.isValid(actName)) {
185
String message = apps.getString(action.getMsg());
186
Object[] args = { prettyFieldName };
188
" Error message will be: "
189
+ MessageFormat.format(message, args));
195
System.out.println("FORM VALIDATION PASSED");
197
System.out.println("FORM VALIDATION FAILED");