KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > struts > validator > FieldChecks


1 /*
2  * $Id: FieldChecks.java 164530 2005-04-25 03:11:07Z niallp $
3  *
4  * Copyright 2000-2005 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 package org.apache.struts.validator;
20
21 import java.io.Serializable JavaDoc;
22 import java.util.Date JavaDoc;
23 import java.util.Locale JavaDoc;
24 import java.util.StringTokenizer JavaDoc;
25
26 import javax.servlet.ServletContext JavaDoc;
27 import javax.servlet.http.HttpServletRequest JavaDoc;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31 import org.apache.commons.validator.Field;
32 import org.apache.commons.validator.GenericTypeValidator;
33 import org.apache.commons.validator.GenericValidator;
34 import org.apache.commons.validator.UrlValidator;
35 import org.apache.commons.validator.Validator;
36 import org.apache.commons.validator.ValidatorAction;
37 import org.apache.commons.validator.util.ValidatorUtils;
38 import org.apache.struts.action.ActionMessages;
39 import org.apache.struts.util.RequestUtils;
40
41 /**
42  * <p>
43  * This class contains the default validations that are used in the
44  * validator-rules.xml file.
45  * </p>
46  * <p>
47  * In general passing in a null or blank will return a null Object or a false
48  * boolean. However, nulls and blanks do not result in an error being added to the
49  * errors.
50  * </p>
51  *
52  * @since Struts 1.1
53  */

54 public class FieldChecks implements Serializable JavaDoc {
55
56     /**
57      * Commons Logging instance.
58      */

59     private static final Log log = LogFactory.getLog(FieldChecks.class);
60
61     public static final String JavaDoc FIELD_TEST_NULL = "NULL";
62     public static final String JavaDoc FIELD_TEST_NOTNULL = "NOTNULL";
63     public static final String JavaDoc FIELD_TEST_EQUAL = "EQUAL";
64
65     /**
66      * Checks if the field isn't null and length of the field is greater than zero not
67      * including whitespace.
68      *
69      * @param bean The bean validation is being performed on.
70      * @param va The <code>ValidatorAction</code> that is currently being performed.
71      * @param field The <code>Field</code> object associated with the current
72      * field being validated.
73      * @param errors The <code>ActionMessages</code> object to add errors to if
74      * any validation errors occur.
75      * @param validator The <code>Validator</code> instance, used to access
76      * other field values.
77      * @param request Current request object.
78      * @return true if meets stated requirements, false otherwise.
79      */

80     public static boolean validateRequired(Object JavaDoc bean,
81                                            ValidatorAction va, Field field,
82                                            ActionMessages errors,
83                                            Validator validator,
84                                            HttpServletRequest JavaDoc request) {
85
86         String JavaDoc value = null;
87         if (isString(bean)) {
88             value = (String JavaDoc) bean;
89         } else {
90             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
91         }
92
93         if (GenericValidator.isBlankOrNull(value)) {
94             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
95             return false;
96         } else {
97             return true;
98         }
99
100     }
101
102     /**
103      * Checks if the field isn't null based on the values of other fields.
104      *
105      * @param bean The bean validation is being performed on.
106      * @param va The <code>ValidatorAction</code> that is currently being
107      * performed.
108      * @param field The <code>Field</code> object associated with the current
109      * field being validated.
110      * @param errors The <code>ActionMessages</code> object to add errors to if
111      * any validation errors occur.
112      * @param validator The <code>Validator</code> instance, used to access
113      * other field values.
114      * @param request Current request object.
115      * @return true if meets stated requirements, false otherwise.
116      */

117     public static boolean validateRequiredIf(Object JavaDoc bean,
118                                              ValidatorAction va, Field field,
119                                              ActionMessages errors,
120                                              Validator validator,
121                                              HttpServletRequest JavaDoc request) {
122
123         Object JavaDoc form = validator.getParameterValue(org.apache.commons.validator.Validator.BEAN_PARAM);
124         String JavaDoc value = null;
125         boolean required = false;
126
127         if (isString(bean)) {
128             value = (String JavaDoc) bean;
129         } else {
130             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
131         }
132
133         int i = 0;
134         String JavaDoc fieldJoin = "AND";
135         if (!GenericValidator.isBlankOrNull(field.getVarValue("fieldJoin"))) {
136             fieldJoin = field.getVarValue("fieldJoin");
137         }
138
139         if (fieldJoin.equalsIgnoreCase("AND")) {
140             required = true;
141         }
142
143         while (!GenericValidator.isBlankOrNull(field.getVarValue("field[" + i + "]"))) {
144             String JavaDoc dependProp = field.getVarValue("field[" + i + "]");
145             String JavaDoc dependTest = field.getVarValue("fieldTest[" + i + "]");
146             String JavaDoc dependTestValue = field.getVarValue("fieldValue[" + i + "]");
147             String JavaDoc dependIndexed = field.getVarValue("fieldIndexed[" + i + "]");
148
149             if (dependIndexed == null) {
150                 dependIndexed = "false";
151             }
152
153             String JavaDoc dependVal = null;
154             boolean thisRequired = false;
155             if (field.isIndexed() && dependIndexed.equalsIgnoreCase("true")) {
156                 String JavaDoc key = field.getKey();
157                 if ((key.indexOf("[") > -1) && (key.indexOf("]") > -1)) {
158                     String JavaDoc ind = key.substring(0, key.indexOf(".") + 1);
159                     dependProp = ind + dependProp;
160                 }
161             }
162
163             dependVal = ValidatorUtils.getValueAsString(form, dependProp);
164             if (dependTest.equals(FIELD_TEST_NULL)) {
165                 if ((dependVal != null) && (dependVal.length() > 0)) {
166                     thisRequired = false;
167                 } else {
168                     thisRequired = true;
169                 }
170             }
171
172             if (dependTest.equals(FIELD_TEST_NOTNULL)) {
173                 if ((dependVal != null) && (dependVal.length() > 0)) {
174                     thisRequired = true;
175                 } else {
176                     thisRequired = false;
177                 }
178             }
179
180             if (dependTest.equals(FIELD_TEST_EQUAL)) {
181                 thisRequired = dependTestValue.equalsIgnoreCase(dependVal);
182             }
183
184             if (fieldJoin.equalsIgnoreCase("AND")) {
185                 required = required && thisRequired;
186             } else {
187                 required = required || thisRequired;
188             }
189
190             i++;
191         }
192
193         if (required) {
194             if (GenericValidator.isBlankOrNull(value)) {
195                 errors.add(
196                     field.getKey(),
197                     Resources.getActionMessage(validator, request, va, field));
198
199                 return false;
200
201             } else {
202                 return true;
203             }
204         }
205         return true;
206     }
207
208     /**
209      * Checks if the field matches the regular expression in the field's mask attribute.
210      *
211      * @param bean The bean validation is being performed on.
212      * @param va The <code>ValidatorAction</code> that is currently being
213      * performed.
214      * @param field The <code>Field</code> object associated with the current
215      * field being validated.
216      * @param errors The <code>ActionMessages</code> object to add errors to if
217      * any validation errors occur.
218      * @param validator The <code>Validator</code> instance, used to access
219      * other field values.
220      * @param request Current request object.
221      * @return true if field matches mask, false otherwise.
222      */

223     public static boolean validateMask(Object JavaDoc bean,
224                                        ValidatorAction va, Field field,
225                                        ActionMessages errors,
226                                        Validator validator,
227                                        HttpServletRequest JavaDoc request) {
228
229         String JavaDoc mask = field.getVarValue("mask");
230         String JavaDoc value = null;
231         if (isString(bean)) {
232             value = (String JavaDoc) bean;
233         } else {
234             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
235         }
236
237         try {
238             if (!GenericValidator.isBlankOrNull(value)
239                 && !GenericValidator.matchRegexp(value, mask)) {
240
241                 errors.add(
242                     field.getKey(),
243                     Resources.getActionMessage(validator, request, va, field));
244
245                 return false;
246             } else {
247                 return true;
248             }
249         } catch (Exception JavaDoc e) {
250             log.error(e.getMessage(), e);
251         }
252         return true;
253     }
254
255
256     /**
257      * Checks if the field can safely be converted to a byte primitive.
258      *
259      *@param bean The bean validation is being performed on.
260      *@param va The <code>ValidatorAction</code> that is currently being performed.
261      *@param field The <code>Field</code> object associated with the current
262      *field being validated.
263      *@param errors The <code>ActionMessages</code> object to add errors to if
264      *any validation errors occur.
265      * @param validator The <code>Validator</code> instance, used to access
266      * other field values.
267      *@param request Current request object.
268      *@return true if valid, false otherwise.
269      */

270     public static Object JavaDoc validateByte(Object JavaDoc bean,
271                                     ValidatorAction va, Field field,
272                                     ActionMessages errors,
273                                     Validator validator,
274                                     HttpServletRequest JavaDoc request) {
275
276         Object JavaDoc result = null;
277         String JavaDoc value = null;
278         if (isString(bean)) {
279             value = (String JavaDoc) bean;
280         } else {
281             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
282         }
283
284         if (GenericValidator.isBlankOrNull(value)) {
285             return Boolean.TRUE;
286         }
287
288         result = GenericTypeValidator.formatByte(value);
289
290         if (result == null) {
291             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
292         }
293
294         return result == null ? Boolean.FALSE : result;
295     }
296
297
298     /**
299      * Checks if the field can safely be converted to a short primitive.
300      *
301      * @param bean The bean validation is being performed on.
302      * @param va The <code>ValidatorAction</code> that is currently being performed.
303      * @param field The <code>Field</code> object associated with the current
304      * field being validated.
305      * @param errors The <code>ActionMessages</code> object to add errors to if
306      * any validation errors occur.
307      * @param validator The <code>Validator</code> instance, used to access
308      * other field values.
309      * @param request Current request object.
310      * @return true if valid, false otherwise.
311      */

312     public static Object JavaDoc validateShort(Object JavaDoc bean,
313                                       ValidatorAction va, Field field,
314                                       ActionMessages errors,
315                                       Validator validator,
316                                       HttpServletRequest JavaDoc request) {
317         Object JavaDoc result = null;
318         String JavaDoc value = null;
319         if (isString(bean)) {
320             value = (String JavaDoc) bean;
321         } else {
322             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
323         }
324
325         if (GenericValidator.isBlankOrNull(value)) {
326             return Boolean.TRUE;
327         }
328
329         result = GenericTypeValidator.formatShort(value);
330
331         if (result == null) {
332             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
333         }
334
335         return result == null ? Boolean.FALSE : result;
336     }
337
338
339     /**
340      * Checks if the field can safely be converted to an int primitive.
341      *
342      * @param bean The bean validation is being performed on.
343      * @param va The <code>ValidatorAction</code> that is currently being performed.
344      * @param field The <code>Field</code> object associated with the current
345      * field being validated.
346      * @param errors The <code>ActionMessages</code> object to add errors to if any
347      * validation errors occur.
348      * @param validator The <code>Validator</code> instance, used to access
349      * other field values.
350      * @param request Current request object.
351      * @return true if valid, false otherwise.
352      */

353     public static Object JavaDoc validateInteger(Object JavaDoc bean,
354                                           ValidatorAction va, Field field,
355                                           ActionMessages errors,
356                                           Validator validator,
357                                           HttpServletRequest JavaDoc request) {
358         Object JavaDoc result = null;
359         String JavaDoc value = null;
360         if (isString(bean)) {
361             value = (String JavaDoc) bean;
362         } else {
363             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
364         }
365
366         if (GenericValidator.isBlankOrNull(value)) {
367             return Boolean.TRUE;
368         }
369
370         result = GenericTypeValidator.formatInt(value);
371
372         if (result == null) {
373             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
374         }
375
376         return result == null ? Boolean.FALSE : result;
377     }
378
379
380     /**
381      * Checks if the field can safely be converted to a long primitive.
382      *
383      * @param bean The bean validation is being performed on.
384      * @param va The <code>ValidatorAction</code> that is currently being performed.
385      * @param field The <code>Field</code> object associated with the current
386      * field being validated.
387      * @param errors The <code>ActionMessages</code> object to add errors to if any
388      * validation errors occur.
389      * @param validator The <code>Validator</code> instance, used to access
390      * other field values.
391      * @param request Current request object.
392      * @return true if valid, false otherwise.
393      */

394     public static Object JavaDoc validateLong(Object JavaDoc bean,
395                                     ValidatorAction va, Field field,
396                                     ActionMessages errors,
397                                     Validator validator,
398                                     HttpServletRequest JavaDoc request) {
399         Object JavaDoc result = null;
400         String JavaDoc value = null;
401         if (isString(bean)) {
402             value = (String JavaDoc) bean;
403         } else {
404             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
405         }
406
407         if (GenericValidator.isBlankOrNull(value)) {
408             return Boolean.TRUE;
409         }
410
411         result = GenericTypeValidator.formatLong(value);
412
413         if (result == null) {
414             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
415         }
416
417         return result == null ? Boolean.FALSE : result;
418     }
419
420
421     /**
422      * Checks if the field can safely be converted to a float primitive.
423      *
424      * @param bean The bean validation is being performed on.
425      * @param va The <code>ValidatorAction</code> that is currently being performed.
426      * @param field The <code>Field</code> object associated with the current
427      * field being validated.
428      * @param errors The <code>ActionMessages</code> object to add errors to if any
429      * validation errors occur.
430      * @param validator The <code>Validator</code> instance, used to access
431      * other field values.
432      * @param request Current request object.
433      * @return true if valid, false otherwise.
434      */

435     public static Object JavaDoc validateFloat(Object JavaDoc bean,
436                                       ValidatorAction va, Field field,
437                                       ActionMessages errors,
438                                       Validator validator,
439                                       HttpServletRequest JavaDoc request) {
440         Object JavaDoc result = null;
441         String JavaDoc value = null;
442         if (isString(bean)) {
443             value = (String JavaDoc) bean;
444         } else {
445             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
446         }
447
448         if (GenericValidator.isBlankOrNull(value)) {
449             return Boolean.TRUE;
450         }
451
452         result = GenericTypeValidator.formatFloat(value);
453
454         if (result == null) {
455             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
456         }
457
458         return result == null ? Boolean.FALSE : result;
459     }
460
461
462     /**
463      * Checks if the field can safely be converted to a double primitive.
464      *
465      * @param bean The bean validation is being performed on.
466      * @param va The <code>ValidatorAction</code> that is currently being performed.
467      * @param field The <code>Field</code> object associated with the current
468      * field being validated.
469      * @param errors The <code>ActionMessages</code> object to add errors to if any
470      * validation errors occur.
471      * @param validator The <code>Validator</code> instance, used to access
472      * other field values.
473      * @param request Current request object.
474      * @return true if valid, false otherwise.
475      */

476     public static Object JavaDoc validateDouble(Object JavaDoc bean,
477                                         ValidatorAction va, Field field,
478                                         ActionMessages errors,
479                                         Validator validator,
480                                         HttpServletRequest JavaDoc request) {
481         Object JavaDoc result = null;
482         String JavaDoc value = null;
483         if (isString(bean)) {
484             value = (String JavaDoc) bean;
485         } else {
486             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
487         }
488
489         if (GenericValidator.isBlankOrNull(value)) {
490             return Boolean.TRUE;
491         }
492
493         result = GenericTypeValidator.formatDouble(value);
494
495         if (result == null) {
496             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
497         }
498
499         return result == null ? Boolean.FALSE : result;
500     }
501
502
503     /**
504      * Checks if the field is a valid date. If the field has a datePattern variable,
505      * that will be used to format <code>java.text.SimpleDateFormat</code>. If the
506      * field has a datePatternStrict variable, that will be used to format <code>java.text.SimpleDateFormat</code>
507      * and the length will be checked so '2/12/1999' will not pass validation with
508      * the format 'MM/dd/yyyy' because the month isn't two digits. If no datePattern
509      * variable is specified, then the field gets the DateFormat.SHORT format for
510      * the locale. The setLenient method is set to <code>false</code> for all variations.
511      *
512      * @param bean The bean validation is being performed on.
513      * @param va The <code>ValidatorAction</code> that is currently being performed.
514      * @param field The <code>Field</code> object associated with the current
515      * field being validated.
516      * @param errors The <code>ActionMessages</code> object to add errors to if any
517      * validation errors occur.
518      * @param validator The <code>Validator</code> instance, used to access
519      * other field values.
520      * @param request Current request object.
521      * @return true if valid, false otherwise.
522      */

523     public static Object JavaDoc validateDate(Object JavaDoc bean,
524                                     ValidatorAction va, Field field,
525                                     ActionMessages errors,
526                                     Validator validator,
527                                     HttpServletRequest JavaDoc request) {
528
529         Object JavaDoc result = null;
530         String JavaDoc value = null;
531         if (isString(bean)) {
532             value = (String JavaDoc) bean;
533         } else {
534             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
535         }
536         String JavaDoc datePattern = field.getVarValue("datePattern");
537         String JavaDoc datePatternStrict = field.getVarValue("datePatternStrict");
538         Locale JavaDoc locale = RequestUtils.getUserLocale(request, null);
539
540         if (GenericValidator.isBlankOrNull(value)) {
541             return Boolean.TRUE;
542         }
543
544         try {
545             if (datePattern != null && datePattern.length() > 0) {
546                 result = GenericTypeValidator.formatDate(value, datePattern, false);
547             } else if (datePatternStrict != null && datePatternStrict.length() > 0) {
548                 result = GenericTypeValidator.formatDate(value, datePatternStrict, true);
549             } else {
550                 result = GenericTypeValidator.formatDate(value, locale);
551             }
552         } catch (Exception JavaDoc e) {
553             log.error(e.getMessage(), e);
554         }
555
556         if (result == null) {
557             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
558         }
559
560         return result == null ? Boolean.FALSE : result;
561     }
562
563     /**
564      * Checks if a fields value is within a range (min &amp; max specified in the
565      * vars attribute).
566      *
567      * @param bean The bean validation is being performed on.
568      * @param va The <code>ValidatorAction</code> that is currently being performed.
569      * @param field The <code>Field</code> object associated with the current
570      * field being validated.
571      * @param errors The <code>ActionMessages</code> object to add errors to if any
572      * validation errors occur.
573      * @param validator The <code>Validator</code> instance, used to access
574      * other field values.
575      * @param request Current request object.
576      * @return True if in range, false otherwise.
577      */

578     public static boolean validateIntRange(Object JavaDoc bean,
579                                            ValidatorAction va, Field field,
580                                            ActionMessages errors,
581                                            Validator validator,
582                                            HttpServletRequest JavaDoc request) {
583
584         String JavaDoc value = null;
585         if (isString(bean)) {
586             value = (String JavaDoc) bean;
587         } else {
588             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
589         }
590
591         if (!GenericValidator.isBlankOrNull(value)) {
592             try {
593                 int intValue = Integer.parseInt(value);
594                 int min = Integer.parseInt(field.getVarValue("min"));
595                 int max = Integer.parseInt(field.getVarValue("max"));
596
597                 if (!GenericValidator.isInRange(intValue, min, max)) {
598                     errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
599
600                     return false;
601                 }
602             } catch (Exception JavaDoc e) {
603                 errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
604                 return false;
605             }
606         }
607
608         return true;
609     }
610
611     /**
612      * Checks if a fields value is within a range (min &amp; max specified in the
613      * vars attribute).
614      *
615      * @param bean The bean validation is being performed on.
616      * @param va The <code>ValidatorAction</code> that is currently being performed.
617      * @param field The <code>Field</code> object associated with the current
618      * field being validated.
619      * @param errors The <code>ActionMessages</code> object to add errors to if any
620      * validation errors occur.
621      * @param validator The <code>Validator</code> instance, used to access
622      * other field values.
623      * @param request Current request object.
624      * @return True if in range, false otherwise.
625      */

626     public static boolean validateDoubleRange(Object JavaDoc bean,
627                                               ValidatorAction va, Field field,
628                                               ActionMessages errors,
629                                               Validator validator,
630                                               HttpServletRequest JavaDoc request) {
631
632         String JavaDoc value = null;
633         if (isString(bean)) {
634             value = (String JavaDoc) bean;
635         } else {
636             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
637         }
638
639         if (!GenericValidator.isBlankOrNull(value)) {
640             try {
641                 double doubleValue = Double.parseDouble(value);
642                 double min = Double.parseDouble(field.getVarValue("min"));
643                 double max = Double.parseDouble(field.getVarValue("max"));
644
645                 if (!GenericValidator.isInRange(doubleValue, min, max)) {
646                     errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
647
648                     return false;
649                 }
650             } catch (Exception JavaDoc e) {
651                 errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
652                 return false;
653             }
654         }
655
656         return true;
657     }
658
659     /**
660      * Checks if a fields value is within a range (min &amp; max specified in the
661      * vars attribute).
662      *
663      * @param bean The bean validation is being performed on.
664      * @param va The <code>ValidatorAction</code> that is currently being performed.
665      * @param field The <code>Field</code> object associated with the current
666      * field being validated.
667      * @param errors The <code>ActionMessages</code> object to add errors to if any
668      * validation errors occur.
669      * @param validator The <code>Validator</code> instance, used to access
670      * other field values.
671      * @param request Current request object.
672      * @return True if in range, false otherwise.
673      */

674     public static boolean validateFloatRange(Object JavaDoc bean,
675                                              ValidatorAction va, Field field,
676                                              ActionMessages errors,
677                                              Validator validator,
678                                              HttpServletRequest JavaDoc request) {
679
680         String JavaDoc value = null;
681         if (isString(bean)) {
682             value = (String JavaDoc) bean;
683         } else {
684             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
685         }
686
687         if (!GenericValidator.isBlankOrNull(value)) {
688             try {
689                 float floatValue = Float.parseFloat(value);
690                 float min = Float.parseFloat(field.getVarValue("min"));
691                 float max = Float.parseFloat(field.getVarValue("max"));
692
693                 if (!GenericValidator.isInRange(floatValue, min, max)) {
694                     errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
695
696                     return false;
697                 }
698             } catch (Exception JavaDoc e) {
699                 errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
700                 return false;
701             }
702         }
703
704         return true;
705     }
706
707
708     /**
709      * Checks if the field is a valid credit card number.
710      *
711      * @param bean The bean validation is being performed on.
712      * @param va The <code>ValidatorAction</code> that is currently being performed.
713      * @param field The <code>Field</code> object associated with the current
714      * field being validated.
715      * @param errors The <code>ActionMessages</code> object to add errors to if any
716      * validation errors occur.
717      * @param validator The <code>Validator</code> instance, used to access
718      * other field values.
719      * @param request Current request object.
720      * @return true if valid, false otherwise.
721      */

722     public static Object JavaDoc validateCreditCard(Object JavaDoc bean,
723                                           ValidatorAction va, Field field,
724                                           ActionMessages errors,
725                                           Validator validator,
726                                           HttpServletRequest JavaDoc request) {
727
728         Object JavaDoc result = null;
729         String JavaDoc value = null;
730         if (isString(bean)) {
731             value = (String JavaDoc) bean;
732         } else {
733             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
734         }
735
736         if (GenericValidator.isBlankOrNull(value)) {
737             return Boolean.TRUE;
738         }
739
740         result = GenericTypeValidator.formatCreditCard(value);
741
742         if (result == null) {
743             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
744         }
745
746         return result == null ? Boolean.FALSE : result;
747
748     }
749
750
751     /**
752      * Checks if a field has a valid e-mail address.
753      *
754      * @param bean The bean validation is being performed on.
755      * @param va The <code>ValidatorAction</code> that is currently being performed.
756      * @param field The <code>Field</code> object associated with the current
757      * field being validated.
758      * @param errors The <code>ActionMessages</code> object to add errors to if any
759      * validation errors occur.
760      * @param validator The <code>Validator</code> instance, used to access
761      * other field values.
762      * @param request Current request object.
763      * @return True if valid, false otherwise.
764      */

765     public static boolean validateEmail(Object JavaDoc bean,
766                                         ValidatorAction va, Field field,
767                                         ActionMessages errors,
768                                         Validator validator,
769                                         HttpServletRequest JavaDoc request) {
770
771         String JavaDoc value = null;
772         if (isString(bean)) {
773             value = (String JavaDoc) bean;
774         } else {
775             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
776         }
777
778         if (!GenericValidator.isBlankOrNull(value) && !GenericValidator.isEmail(value)) {
779             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
780             return false;
781         } else {
782             return true;
783         }
784     }
785
786
787     /**
788      * Checks if the field's length is less than or equal to the maximum value.
789      * A <code>Null</code> will be considered an error.
790      *
791      * @param bean The bean validation is being performed on.
792      * @param va The <code>ValidatorAction</code> that is currently being performed.
793      * @param field The <code>Field</code> object associated with the current
794      * field being validated.
795      * @param errors The <code>ActionMessages</code> object to add errors to if any
796      * validation errors occur.
797      * @param validator The <code>Validator</code> instance, used to access
798      * other field values.
799      * @param request Current request object.
800      * @return True if stated conditions met.
801      */

802     public static boolean validateMaxLength(Object JavaDoc bean,
803                                             ValidatorAction va, Field field,
804                                             ActionMessages errors,
805                                             Validator validator,
806                                             HttpServletRequest JavaDoc request) {
807
808         String JavaDoc value = null;
809         if (isString(bean)) {
810             value = (String JavaDoc) bean;
811         } else {
812             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
813         }
814
815         if (value != null) {
816             try {
817                 int max = Integer.parseInt(field.getVarValue("maxlength"));
818
819                 if (!GenericValidator.maxLength(value, max)) {
820                     errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
821
822                     return false;
823                 }
824             } catch (Exception JavaDoc e) {
825                 errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
826                 return false;
827             }
828         }
829
830         return true;
831     }
832
833
834     /**
835      * Checks if the field's length is greater than or equal to the minimum value.
836      * A <code>Null</code> will be considered an error.
837      *
838      * @param bean The bean validation is being performed on.
839      * @param va The <code>ValidatorAction</code> that is currently being performed.
840      * @param field The <code>Field</code> object associated with the current
841      * field being validated.
842      * @param errors The <code>ActionMessages</code> object to add errors to if any
843      * validation errors occur.
844      * @param validator The <code>Validator</code> instance, used to access
845      * other field values.
846      * @param request Current request object.
847      * @return True if stated conditions met.
848      */

849     public static boolean validateMinLength(Object JavaDoc bean,
850                                             ValidatorAction va, Field field,
851                                             ActionMessages errors,
852                                             Validator validator,
853                                             HttpServletRequest JavaDoc request) {
854
855         String JavaDoc value = null;
856         if (isString(bean)) {
857             value = (String JavaDoc) bean;
858         } else {
859             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
860         }
861
862         if (!GenericValidator.isBlankOrNull(value)) {
863             try {
864                 int min = Integer.parseInt(field.getVarValue("minlength"));
865
866                 if (!GenericValidator.minLength(value, min)) {
867                     errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
868
869                     return false;
870                 }
871             } catch (Exception JavaDoc e) {
872                 errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
873                 return false;
874             }
875         }
876
877         return true;
878     }
879
880     /**
881      * Checks if a field has a valid url. Four optional variables can be
882      * specified to configure url validation.
883      * <ul>
884      * <li>Variable <code>allow2slashes</code> can be set to <code>true</code> or
885      * <code>false</code> to control whether two slashes are allowed -
886      * default is <code>false</code> (i.e. two slashes are NOT allowed).</li>
887      * <li>Variable <code>nofragments</code> can be set to <code>true</code> or
888      * <code>false</code> to control whether fragments are allowed -
889      * default is <code>false</code> (i.e. fragments ARE allowed).</li>
890      * <li>Variable <code>allowallschemes</code> can be set to <code>true</code> or
891      * <code>false</code> to control if all schemes are allowed - default
892      * is <code>false</code> (i.e. all schemes are NOT allowed).</li>
893      * <li>Variable <code>schemes</code> can be set to a comma delimited list of
894      * valid schemes. This value is ignored if <code>allowallschemes</code>
895      * is set to <code>true</code>. Default schemes allowed are "http",
896      * "https" and "ftp" if this variable is not specified.</li>
897      * </ul>
898      *
899      * @param bean The bean validation is being performed on.
900      * @param va The <code>ValidatorAction</code> that is currently being performed.
901      * @param field The <code>Field</code> object associated with the current
902      * field being validated.
903      * @param errors The <code>ActionMessages</code> object to add errors to if any
904      * validation errors occur.
905      * @param validator The <code>Validator</code> instance, used to access
906      * other field values.
907      * @param request Current request object.
908      * @return True if valid, false otherwise.
909      */

910     public static boolean validateUrl(Object JavaDoc bean,
911                                         ValidatorAction va, Field field,
912                                         ActionMessages errors,
913                                         Validator validator,
914                                         HttpServletRequest JavaDoc request) {
915
916         String JavaDoc value = null;
917         if (isString(bean)) {
918             value = (String JavaDoc) bean;
919         } else {
920             value = ValidatorUtils.getValueAsString(bean, field.getProperty());
921         }
922
923         if (GenericValidator.isBlankOrNull(value)) {
924             return true;
925         }
926
927         // Get the options and schemes Vars
928
boolean allowallschemes = "true".equalsIgnoreCase(field.getVarValue("allowallschemes"));
929         int options = allowallschemes ? UrlValidator.ALLOW_ALL_SCHEMES : 0;
930
931         if ("true".equalsIgnoreCase(field.getVarValue("allow2slashes"))) {
932           options += UrlValidator.ALLOW_2_SLASHES;
933         }
934
935         if ("true".equalsIgnoreCase(field.getVarValue("nofragments"))) {
936           options += UrlValidator.NO_FRAGMENTS;
937         }
938
939         String JavaDoc schemesVar = allowallschemes ? null : field.getVarValue("schemes");
940
941         // No options or schemes - use GenericValidator as default
942
if (options == 0 && schemesVar == null) {
943             if (GenericValidator.isUrl(value)) {
944                 return true;
945             } else {
946                 errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
947                 return false;
948             }
949         }
950
951         // Parse comma delimited list of schemes into a String[]
952
String JavaDoc[] schemes = null;
953         if (schemesVar != null) {
954
955           StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(schemesVar, ",");
956           schemes = new String JavaDoc[st.countTokens()];
957
958           int i = 0;
959           while (st.hasMoreTokens()) {
960               schemes[i++] = st.nextToken().trim();
961           }
962
963         }
964
965         // Create UrlValidator and validate with options/schemes
966
UrlValidator urlValidator = new UrlValidator(schemes, options);
967         if (urlValidator.isValid(value)) {
968             return true;
969         } else {
970             errors.add(field.getKey(), Resources.getActionMessage(validator, request, va, field));
971             return false;
972         }
973     }
974
975     /**
976      * Return <code>true</code> if the specified object is a String or a <code>null</code>
977      * value.
978      *
979      * @param o Object to be tested
980      * @return The string value
981      */

982     protected static boolean isString(Object JavaDoc o) {
983         return (o == null) ? true : String JavaDoc.class.isInstance(o);
984     }
985
986 }
987
988
Popular Tags