KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jdon > util > UtilValidate


1 /*
2  * $Id: UtilValidate.java,v 1.2 2005/01/31 05:27:55 jdon Exp $
3  *
4  * Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24
25 package com.jdon.util;
26
27
28 import java.util.Calendar JavaDoc;
29 import java.util.Collection JavaDoc;
30
31
32 /**
33  * <p>General input/data validation methods
34  * <p>Utility methods for validating data, especially input. See detailed description below.
35  *
36  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
37  * @created May 21, 2001
38  * @version 1.0
39  *
40  *
41  * <br> SUMMARY
42  * <br>
43  * <br> This is a set of meethods for validating input. Functions are provided to validate:
44  * <br> - U.S. and international phone/fax numbers
45  * <br> - U.S. ZIP codes(5 or 9 digit postal codes)
46  * <br> - U.S. Postal Codes(2 letter abbreviations for names of states)
47  * <br> - U.S. Social Security Numbers(abbreviated as SSNs)
48  * <br> - email addresses
49  * <br> - dates(entry of year, month, and day and validity of combined date)
50  * <br> - credit card numbers
51  * <br>
52  * <br> Supporting utility functions validate that:
53  * <br> - characters are Letter, Digit, or LetterOrDigit
54  * <br> - strings are a Signed, Positive, Negative, Nonpositive, or Nonnegative integer
55  * <br> - strings are a Float or a SignedFloat
56  * <br> - strings are Alphabetic, Alphanumeric, or Whitespace
57  * <br> - strings contain an integer within a specified range
58  * <br>
59  * <br> Other utility functions are provided to:
60  * <br> - remove from a string characters which are/are not in a "bag" of selected characters
61  * <br> - strip whitespace/leading whitespace from a string
62  * <br>
63  * <br> ================================================================
64  * <br> NOTE: This code was adapted from the Netscape JavaScript form validation code, usually found in "FormChek.js".
65  * <br> Credit card verification functions Originally included as Starter Application 1.0.0 in LivePayment.
66  * <br> ================================================================
67  */

68 public class UtilValidate {
69
70     /** boolean specifying by default whether or not it is okay for a String to be empty */
71     public static final boolean defaultEmptyOK = true;
72
73     /** digit characters */
74     public static final String JavaDoc digits = "0123456789";
75
76     /** lower-case letter characters */
77     public static final String JavaDoc lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
78
79     /** upper-case letter characters */
80     public static final String JavaDoc uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
81
82     /** letter characters */
83     public static final String JavaDoc letters = lowercaseLetters + uppercaseLetters;
84
85     /** whitespace characters */
86     public static final String JavaDoc whitespace = " \t\n\r";
87
88     /** decimal point character differs by language and culture */
89     public static final String JavaDoc decimalPointDelimiter = ".";
90
91     /** non-digit characters which are allowed in phone numbers */
92     public static final String JavaDoc phoneNumberDelimiters = "()- ";
93
94     /** characters which are allowed in US phone numbers */
95     public static final String JavaDoc validUSPhoneChars = digits + phoneNumberDelimiters;
96
97     /** characters which are allowed in international phone numbers(a leading + is OK) */
98     public static final String JavaDoc validWorldPhoneChars = digits + phoneNumberDelimiters + "+";
99
100     /** non-digit characters which are allowed in Social Security Numbers */
101     public static final String JavaDoc SSNDelimiters = "- ";
102
103     /** characters which are allowed in Social Security Numbers */
104     public static final String JavaDoc validSSNChars = digits + SSNDelimiters;
105
106     /** U.S. Social Security Numbers have 9 digits. They are formatted as 123-45-6789. */
107     public static final int digitsInSocialSecurityNumber = 9;
108
109     /** U.S. phone numbers have 10 digits. They are formatted as 123 456 7890 or(123) 456-7890. */
110     public static final int digitsInUSPhoneNumber = 10;
111     public static final int digitsInUSPhoneAreaCode = 3;
112     public static final int digitsInUSPhoneMainNumber = 7;
113
114     /** non-digit characters which are allowed in ZIP Codes */
115     public static final String JavaDoc ZipCodeDelimiters = "-";
116
117     /** our preferred delimiter for reformatting ZIP Codes */
118     public static final String JavaDoc ZipCodeDelimeter = "-";
119
120     /** characters which are allowed in Social Security Numbers */
121     public static final String JavaDoc validZipCodeChars = digits + ZipCodeDelimiters;
122
123     /** U.S. ZIP codes have 5 or 9 digits. They are formatted as 12345 or 12345-6789. */
124     public static final int digitsInZipCode1 = 5;
125
126     /** U.S. ZIP codes have 5 or 9 digits. They are formatted as 12345 or 12345-6789. */
127     public static final int digitsInZipCode2 = 9;
128
129     /** non-digit characters which are allowed in credit card numbers */
130     public static final String JavaDoc creditCardDelimiters = " -";
131
132     public static final String JavaDoc isNotEmptyMsg = "This field cannot be empty, please enter a value.";
133     public static final String JavaDoc isStateCodeMsg = "The State Code must be a valid two character U.S. state abbreviation(like CA for California).";
134     public static final String JavaDoc isContiguousStateCodeMsg = "The State Code must be a valid two character U.S. state abbreviation for one of the 48 contiguous United States (like CA for California).";
135     public static final String JavaDoc isZipCodeMsg = "The ZIP Code must be a 5 or 9 digit U.S. ZIP Code(like 94043).";
136     public static final String JavaDoc isUSPhoneMsg = "The US Phone must be a 10 digit U.S. phone number(like 415-555-1212).";
137     public static final String JavaDoc isUSPhoneAreaCodeMsg = "The Phone Number Area Code must be 3 digits.";
138     public static final String JavaDoc isUSPhoneMainNumberMsg = "The Phone Number must be 7 digits.";
139     public static final String JavaDoc isContiguousZipCodeMsg = "Zip Code is not a valid Zip Code for one of the 48 contiguous United States .";
140     public static final String JavaDoc isInternationalPhoneNumberMsg = "The World Phone must be a valid international phone number.";
141     public static final String JavaDoc isSSNMsg = "The SSN must be a 9 digit U.S. social security number(like 123-45-6789).";
142     public static final String JavaDoc isEmailMsg = "The Email must be a valid email address(like john@email.com). Please re-enter it now.";
143     public static final String JavaDoc isAnyCardMsg = "The credit card number is not a valid card number.";
144     public static final String JavaDoc isCreditCardPrefixMsg = " is not a valid ";
145     public static final String JavaDoc isCreditCardSuffixMsg = " credit card number.";
146     public static final String JavaDoc isDayMsg = "The Day must be a day number between 1 and 31. ";
147     public static final String JavaDoc isMonthMsg = "The Month must be a month number between 1 and 12. ";
148     public static final String JavaDoc isYearMsg = "The Year must be a 2 or 4 digit year number. ";
149     public static final String JavaDoc isDatePrefixMsg = "The Day, Month, and Year for ";
150     public static final String JavaDoc isDateSuffixMsg = " do not form a valid date. Please reenter them now.";
151     public static final String JavaDoc isHourMsg = "The Hour must be a number between 0 and 23.";
152     public static final String JavaDoc isMinuteMsg = "The Hour must be a number between 0 and 59.";
153     public static final String JavaDoc isSecondMsg = "The Hour must be a number between 0 and 59.";
154     public static final String JavaDoc isTimeMsg = "The Time must be a valid time formed like: HH:MM or HH:MM:SS.";
155     public static final String JavaDoc isDateMsg = "The Date must be a valid date formed like: MM/YY, MM/YYYY, MM/DD/YY, or MM/DD/YYYY.";
156     public static final String JavaDoc isDateAfterToday = "The Date must be a valid date after today, and formed like: MM/YY, MM/YYYY, MM/DD/YY, or MM/DD/YYYY.";
157     public static final String JavaDoc isIntegerMsg = "The Number must be a valid unsigned whole decimal number.";
158     public static final String JavaDoc isSignedIntegerMsg = "The Number must be a valid signed whole decimal number.";
159     public static final String JavaDoc isLongMsg = "The Number must be a valid unsigned whole decimal number.";
160     public static final String JavaDoc isSignedLongMsg = "The Number must be a valid signed whole decimal number.";
161     public static final String JavaDoc isFloatMsg = "The Number must be a valid unsigned decimal number.";
162     public static final String JavaDoc isSignedFloatMsg = "The Number must be a valid signed decimal number.";
163     public static final String JavaDoc isSignedDoubleMsg = "The Number must be a valid signed decimal number.";
164
165     /** An array of ints representing the number of days in each month of the year.
166      * Note: February varies depending on the year */

167     public static final int[] daysInMonth = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
168
169     /** Delimiter for USStateCodes String */
170     public static final String JavaDoc USStateCodeDelimiter = "|";
171
172     /** Valid U.S. Postal Codes for states, territories, armed forces, etc.
173      * See http://www.usps.gov/ncsc/lookups/abbr_state.txt. */

174     public static final String JavaDoc USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP";
175
176     /** Valid contiguous U.S. postal codes */
177     public static final String JavaDoc ContiguousUSStateCodes = "AL|AZ|AR|CA|CO|CT|DE|DC|FL|GA|ID|IL|IN|IA|KS|KY|LA|ME|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VT|VA|WA|WV|WI|WY";
178
179     public static boolean areEqual(Object JavaDoc obj, Object JavaDoc obj2) {
180         if (obj == null) {
181             return obj2 == null;
182         } else {
183             return obj.equals(obj2);
184         }
185     }
186
187     /** Check whether string s is empty. */
188     public static boolean isEmpty(String JavaDoc s) {
189         return ((s == null) || (s.length() == 0));
190     }
191
192
193     /** Check whether collection c is empty. */
194     public static boolean isEmpty(Collection JavaDoc c) {
195         return ((c == null) || (c.size() == 0));
196     }
197
198     /** Check whether string s is NOT empty. */
199     public static boolean isNotEmpty(String JavaDoc s) {
200         return ((s != null) && (s.length() > 0));
201     }
202
203     /** Check whether collection c is NOT empty. */
204     public static boolean isNotEmpty(Collection JavaDoc c) {
205         return ((c != null) && (c.size() > 0));
206     }
207
208     /** Returns true if string s is empty or whitespace characters only. */
209     public static boolean isWhitespace(String JavaDoc s) {
210         // Is s empty?
211
if (isEmpty(s)) return true;
212
213         // Search through string's characters one by one
214
// until we find a non-whitespace character.
215
// When we do, return false; if we don't, return true.
216
for (int i = 0; i < s.length(); i++) {
217             // Check that current character isn't whitespace.
218
char c = s.charAt(i);
219
220             if (whitespace.indexOf(c) == -1) return false;
221         }
222         // All characters are whitespace.
223
return true;
224     }
225
226     /** Removes all characters which appear in string bag from string s. */
227     public static String JavaDoc stripCharsInBag(String JavaDoc s, String JavaDoc bag) {
228         int i;
229         String JavaDoc returnString = "";
230
231         // Search through string's characters one by one.
232
// If character is not in bag, append to returnString.
233
for (i = 0; i < s.length(); i++) {
234             char c = s.charAt(i);
235
236             if (bag.indexOf(c) == -1) returnString += c;
237         }
238         return returnString;
239     }
240
241     /** Removes all characters which do NOT appear in string bag from string s. */
242     public static String JavaDoc stripCharsNotInBag(String JavaDoc s, String JavaDoc bag) {
243         int i;
244         String JavaDoc returnString = "";
245
246         // Search through string's characters one by one.
247
// If character is in bag, append to returnString.
248
for (i = 0; i < s.length(); i++) {
249             char c = s.charAt(i);
250
251             if (bag.indexOf(c) != -1) returnString += c;
252         }
253         return returnString;
254     }
255
256     /** Removes all whitespace characters from s.
257      * Member whitespace(see above) defines which characters are considered whitespace. */

258     public static String JavaDoc stripWhitespace(String JavaDoc s) {
259         return stripCharsInBag(s, whitespace);
260     }
261
262     /** Returns true if single character c(actually a string) is contained within string s. */
263     public static boolean charInString(char c, String JavaDoc s) {
264         return (s.indexOf(c) != -1);
265         // for(int i = 0; i < s.length; i++) {
266
// if(s.charAt(i) == c) return true;
267
// }
268
// return false;
269
}
270
271     /** Removes initial(leading) whitespace characters from s.
272      * Member whitespace(see above) defines which characters are considered whitespace. */

273     public static String JavaDoc stripInitialWhitespace(String JavaDoc s) {
274         int i = 0;
275
276         while ((i < s.length()) && charInString(s.charAt(i), whitespace)) i++;
277         return s.substring(i);
278         // return s.substring(i, s.length);
279
}
280
281     /** Returns true if character c is an English letter (A .. Z, a..z).
282      *
283      * NOTE: Need i18n version to support European characters.
284      * This could be tricky due to different character
285      * sets and orderings for various languages and platforms. */

286     public static boolean isLetter(char c) {
287         return Character.isLetter(c);
288     }
289
290     /** Returns true if character c is a digit (0 .. 9). */
291     public static boolean isDigit(char c) {
292         return Character.isDigit(c);
293     }
294
295     /** Returns true if character c is a letter or digit. */
296     public static boolean isLetterOrDigit(char c) {
297         return Character.isLetterOrDigit(c);
298     }
299
300     /** Returns true if all characters in string s are numbers.
301      *
302      * Accepts non-signed integers only. Does not accept floating
303      * point, exponential notation, etc.
304      */

305     public static boolean isInteger(String JavaDoc s) {
306         if (isEmpty(s)) return defaultEmptyOK;
307
308         // Search through string's characters one by one
309
// until we find a non-numeric character.
310
// When we do, return false; if we don't, return true.
311
for (int i = 0; i < s.length(); i++) {
312             // Check that current character is number.
313
char c = s.charAt(i);
314
315             if (!isDigit(c)) return false;
316         }
317
318         // All characters are numbers.
319
return true;
320     }
321
322     /** Returns true if all characters are numbers;
323      * first character is allowed to be + or - as well.
324      *
325      * Does not accept floating point, exponential notation, etc.
326      */

327     public static boolean isSignedInteger(String JavaDoc s) {
328         if (isEmpty(s)) return defaultEmptyOK;
329
330         try {
331             int temp = Integer.parseInt(s);
332
333             return true;
334         } catch (Exception JavaDoc e) {
335             return false;
336         }
337
338         // int startPos = 0;
339
// boolean secondArg = defaultEmptyOK;
340

341         // if(isSignedInteger.arguments.length > 1) secondArg = isSignedInteger.arguments[1];
342

343         // skip leading + or -
344
// if((s.charAt(0) == "-") ||(s.charAt(0) == "+") ) startPos = 1;
345
// return(isInteger(s.substring(startPos, s.length), secondArg))
346
}
347
348     /** Returns true if all characters are numbers;
349      * first character is allowed to be + or - as well.
350      *
351      * Does not accept floating point, exponential notation, etc.
352      */

353     public static boolean isSignedLong(String JavaDoc s) {
354         if (isEmpty(s)) return defaultEmptyOK;
355
356         try {
357             long temp = Long.parseLong(s);
358
359             return true;
360         } catch (Exception JavaDoc e) {
361             return false;
362         }
363     }
364
365     /** Returns true if string s is an integer > 0. NOTE: using the Java Long object for greatest precision */
366     public static boolean isPositiveInteger(String JavaDoc s) {
367         if (isEmpty(s)) return defaultEmptyOK;
368
369         try {
370             long temp = Long.parseLong(s);
371
372             if (temp > 0) return true;
373             return false;
374         } catch (Exception JavaDoc e) {
375             return false;
376         }
377
378         // return(isSignedInteger(s, secondArg)
379
// &&((isEmpty(s) && secondArg) ||(parseInt(s) > 0) ) );
380
}
381
382     /** Returns true if string s is an integer >= 0. */
383     public static boolean isNonnegativeInteger(String JavaDoc s) {
384         if (isEmpty(s)) return defaultEmptyOK;
385
386         try {
387             int temp = Integer.parseInt(s);
388
389             if (temp >= 0) return true;
390             return false;
391         } catch (Exception JavaDoc e) {
392             return false;
393         }
394
395         // return(isSignedInteger(s, secondArg)
396
// &&((isEmpty(s) && secondArg) ||(parseInt(s) >= 0) ) );
397
}
398
399     /** Returns true if string s is an integer < 0. */
400     public static boolean isNegativeInteger(String JavaDoc s) {
401         if (isEmpty(s)) return defaultEmptyOK;
402
403         try {
404             int temp = Integer.parseInt(s);
405
406             if (temp < 0) return true;
407             return false;
408         } catch (Exception JavaDoc e) {
409             return false;
410         }
411
412         // return(isSignedInteger(s, secondArg)
413
// &&((isEmpty(s) && secondArg) ||(parseInt(s) < 0) ) );
414
}
415
416     /** Returns true if string s is an integer <= 0. */
417     public static boolean isNonpositiveInteger(String JavaDoc s) {
418         if (isEmpty(s)) return defaultEmptyOK;
419
420         try {
421             int temp = Integer.parseInt(s);
422
423             if (temp <= 0) return true;
424             return false;
425         } catch (Exception JavaDoc e) {
426             return false;
427         }
428
429         // return(isSignedInteger(s, secondArg)
430
// &&((isEmpty(s) && secondArg) ||(parseInt(s) <= 0) ) );
431
}
432
433     /** True if string s is an unsigned floating point(real) number.
434      *
435      * Also returns true for unsigned integers. If you wish
436      * to distinguish between integers and floating point numbers,
437      * first call isInteger, then call isFloat.
438      *
439      * Does not accept exponential notation.
440      */

441     public static boolean isFloat(String JavaDoc s) {
442         if (isEmpty(s)) return defaultEmptyOK;
443
444         boolean seenDecimalPoint = false;
445
446         if (s.startsWith(decimalPointDelimiter)) return false;
447
448         // Search through string's characters one by one
449
// until we find a non-numeric character.
450
// When we do, return false; if we don't, return true.
451
for (int i = 0; i < s.length(); i++) {
452             // Check that current character is number.
453
char c = s.charAt(i);
454
455             if (c == decimalPointDelimiter.charAt(0)) {
456                 if (!seenDecimalPoint)
457                     seenDecimalPoint = true;
458                 else
459                     return false;
460             } else {
461                 if (!isDigit(c)) return false;
462             }
463         }
464         // All characters are numbers.
465
return true;
466     }
467
468     /** True if string s is a signed or unsigned floating point
469      * (real) number. First character is allowed to be + or -.
470      *
471      * Also returns true for unsigned integers. If you wish
472      * to distinguish between integers and floating point numbers,
473      * first call isSignedInteger, then call isSignedFloat.
474      */

475     public static boolean isSignedFloat(String JavaDoc s) {
476         if (isEmpty(s)) return defaultEmptyOK;
477
478         try {
479             float temp = Float.parseFloat(s);
480
481             if (temp <= 0) return true;
482             return false;
483         } catch (Exception JavaDoc e) {
484             return false;
485         }
486
487         // int startPos = 0;
488
// if(isSignedFloat.arguments.length > 1) secondArg = isSignedFloat.arguments[1];
489
// skip leading + or -
490
// if((s.charAt(0) == "-") ||(s.charAt(0) == "+") ) startPos = 1;
491
// return(isFloat(s.substring(startPos, s.length), secondArg))
492
}
493
494     /** True if string s is a signed or unsigned floating point
495      * (real) number. First character is allowed to be + or -.
496      *
497      * Also returns true for unsigned integers. If you wish
498      * to distinguish between integers and floating point numbers,
499      * first call isSignedInteger, then call isSignedFloat.
500      */

501     public static boolean isSignedDouble(String JavaDoc s) {
502         if (isEmpty(s)) return defaultEmptyOK;
503
504         try {
505             double temp = Double.parseDouble(s);
506
507             return true;
508         } catch (Exception JavaDoc e) {
509             return false;
510         }
511     }
512
513     /** Returns true if string s is letters only.
514      *
515      * NOTE: This should handle i18n version to support European characters, etc.
516      * since it now uses Character.isLetter()
517      */

518     public static boolean isAlphabetic(String JavaDoc s) {
519         if (isEmpty(s)) return defaultEmptyOK;
520
521         // Search through string's characters one by one
522
// until we find a non-alphabetic character.
523
// When we do, return false; if we don't, return true.
524
for (int i = 0; i < s.length(); i++) {
525             // Check that current character is letter.
526
char c = s.charAt(i);
527
528             if (!isLetter(c))
529                 return false;
530         }
531
532         // All characters are letters.
533
return true;
534     }
535
536     /** Returns true if string s is English letters (A .. Z, a..z) and numbers only.
537      *
538      * NOTE: Need i18n version to support European characters.
539      * This could be tricky due to different character
540      * sets and orderings for various languages and platforms.
541      */

542     public static boolean isAlphanumeric(String JavaDoc s) {
543         if (isEmpty(s)) return defaultEmptyOK;
544
545         // Search through string's characters one by one
546
// until we find a non-alphanumeric character.
547
// When we do, return false; if we don't, return true.
548
for (int i = 0; i < s.length(); i++) {
549             // Check that current character is number or letter.
550
char c = s.charAt(i);
551
552             if (!isLetterOrDigit(c)) return false;
553         }
554
555         // All characters are numbers or letters.
556
return true;
557     }
558
559     /* ================== METHODS TO CHECK VARIOUS FIELDS. ==================== */
560
561     /** isSSN returns true if string s is a valid U.S. Social Security Number. Must be 9 digits. */
562     public static boolean isSSN(String JavaDoc s) {
563         if (isEmpty(s)) return defaultEmptyOK;
564
565         String JavaDoc normalizedSSN = stripCharsInBag(s, SSNDelimiters);
566
567         return (isInteger(normalizedSSN) && normalizedSSN.length() == digitsInSocialSecurityNumber);
568     }
569
570     /** isUSPhoneNumber returns true if string s is a valid U.S. Phone Number. Must be 10 digits. */
571     public static boolean isUSPhoneNumber(String JavaDoc s) {
572         if (isEmpty(s)) return defaultEmptyOK;
573         String JavaDoc normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters);
574
575         return (isInteger(normalizedPhone) && normalizedPhone.length() == digitsInUSPhoneNumber);
576     }
577
578     /** isUSPhoneAreaCode returns true if string s is a valid U.S. Phone Area Code. Must be 3 digits. */
579     public static boolean isUSPhoneAreaCode(String JavaDoc s) {
580         if (isEmpty(s)) return defaultEmptyOK;
581         String JavaDoc normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters);
582
583         return (isInteger(normalizedPhone) && normalizedPhone.length() == digitsInUSPhoneAreaCode);
584     }
585
586     /** isUSPhoneMainNumber returns true if string s is a valid U.S. Phone Main Number. Must be 7 digits. */
587     public static boolean isUSPhoneMainNumber(String JavaDoc s) {
588         if (isEmpty(s)) return defaultEmptyOK;
589         String JavaDoc normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters);
590
591         return (isInteger(normalizedPhone) && normalizedPhone.length() == digitsInUSPhoneMainNumber);
592     }
593
594     /** isInternationalPhoneNumber returns true if string s is a valid
595      * international phone number. Must be digits only; any length OK.
596      * May be prefixed by + character.
597      */

598     public static boolean isInternationalPhoneNumber(String JavaDoc s) {
599         if (isEmpty(s)) return defaultEmptyOK;
600
601         String JavaDoc normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters);
602
603         return isPositiveInteger(normalizedPhone);
604     }
605
606     /** isZIPCode returns true if string s is a valid U.S. ZIP code. Must be 5 or 9 digits only. */
607     public static boolean isZipCode(String JavaDoc s) {
608         if (isEmpty(s)) return defaultEmptyOK;
609
610         String JavaDoc normalizedZip = stripCharsInBag(s, ZipCodeDelimiters);
611
612         return (isInteger(normalizedZip) && ((normalizedZip.length() == digitsInZipCode1) || (normalizedZip.length() == digitsInZipCode2)));
613     }
614
615     /** Returns true if string s is a valid contiguous U.S. Zip code. Must be 5 or 9 digits only. */
616     public static boolean isContiguousZipCode(String JavaDoc s) {
617         boolean retval = false;
618         if (isZipCode(s)) {
619             if (isEmpty(s)) retval = defaultEmptyOK;
620             else {
621                 String JavaDoc normalizedZip = s.substring(0,5);
622                 int iZip = Integer.parseInt(normalizedZip);
623                 if ((iZip >= 96701 && iZip <= 96898) || (iZip >= 99501 && iZip <= 99950)) retval = false;
624                 else retval = true;
625             }
626         }
627         return retval;
628     }
629
630     /** Return true if s is a valid U.S. Postal Code (abbreviation for state). */
631     public static boolean isStateCode(String JavaDoc s) {
632         if (isEmpty(s)) return defaultEmptyOK;
633         return ((USStateCodes.indexOf(s) != -1) && (s.indexOf(USStateCodeDelimiter) == -1));
634     }
635
636     /** Return true if s is a valid contiguous U.S. Postal Code (abbreviation for state). */
637     public static boolean isContiguousStateCode(String JavaDoc s) {
638         if (isEmpty(s)) return defaultEmptyOK;
639         return ((ContiguousUSStateCodes.indexOf(s) != -1) && (s.indexOf(USStateCodeDelimiter) == -1));
640     }
641
642     /** Email address must be of form a@b.c -- in other words:
643      * - there must be at least one character before the @
644      * - there must be at least one character before and after the .
645      * - the characters @ and . are both required
646      */

647     public static boolean isEmail(String JavaDoc s) {
648         if (isEmpty(s)) return defaultEmptyOK;
649
650         // is s whitespace?
651
if (isWhitespace(s)) return false;
652
653         // there must be >= 1 character before @, so we
654
// start looking at character position 1
655
// (i.e. second character)
656
int i = 1;
657         int sLength = s.length();
658
659         // look for @
660
while ((i < sLength) && (s.charAt(i) != '@')) i++;
661
662         // there must be at least one character after the .
663
if ((i >= sLength - 1) || (s.charAt(i) != '@'))
664             return false;
665         else
666             return true;
667
668         // DEJ 2001-10-13 Don't look for '.', some valid emails do not have a dot in the domain name
669
// else i += 2;
670

671         // look for .
672
// while((i < sLength) && (s.charAt(i) != '.')) i++;
673
// there must be at least one character after the .
674
// if((i >= sLength - 1) || (s.charAt(i) != '.')) return false;
675
// else return true;
676
}
677
678     /** isYear returns true if string s is a valid
679      * Year number. Must be 2 or 4 digits only.
680      *
681      * For Year 2000 compliance, you are advised
682      * to use 4-digit year numbers everywhere.
683      */

684     public static boolean isYear(String JavaDoc s) {
685         if (isEmpty(s)) return defaultEmptyOK;
686
687         if (!isNonnegativeInteger(s)) return false;
688         return ((s.length() == 2) || (s.length() == 4));
689     }
690
691     /** isIntegerInRange returns true if string s is an integer
692      * within the range of integer arguments a and b, inclusive.
693      */

694     public static boolean isIntegerInRange(String JavaDoc s, int a, int b) {
695         if (isEmpty(s)) return defaultEmptyOK;
696         // Catch non-integer strings to avoid creating a NaN below,
697
// which isn't available on JavaScript 1.0 for Windows.
698
if (!isSignedInteger(s)) return false;
699         // Now, explicitly change the type to integer via parseInt
700
// so that the comparison code below will work both on
701
// JavaScript 1.2(which typechecks in equality comparisons)
702
// and JavaScript 1.1 and before(which doesn't).
703
int num = Integer.parseInt(s);
704
705         return ((num >= a) && (num <= b));
706     }
707
708     /** isMonth returns true if string s is a valid month number between 1 and 12. */
709     public static boolean isMonth(String JavaDoc s) {
710         if (isEmpty(s)) return defaultEmptyOK;
711         return isIntegerInRange(s, 1, 12);
712     }
713
714     /** isDay returns true if string s is a valid day number between 1 and 31. */
715     public static boolean isDay(String JavaDoc s) {
716         if (isEmpty(s)) return defaultEmptyOK;
717         return isIntegerInRange(s, 1, 31);
718     }
719
720     /** Given integer argument year, returns number of days in February of that year. */
721     public static int daysInFebruary(int year) {
722         // February has 29 days in any year evenly divisible by four,
723
// EXCEPT for centurial years which are not also divisible by 400.
724
return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
725     }
726
727     /** isHour returns true if string s is a valid number between 0 and 23. */
728     public static boolean isHour(String JavaDoc s) {
729         if (isEmpty(s)) return defaultEmptyOK;
730         return isIntegerInRange(s, 0, 23);
731     }
732
733     /** isMinute returns true if string s is a valid number between 0 and 59. */
734     public static boolean isMinute(String JavaDoc s) {
735         if (isEmpty(s)) return defaultEmptyOK;
736         return isIntegerInRange(s, 0, 59);
737     }
738
739     /** isSecond returns true if string s is a valid number between 0 and 59. */
740     public static boolean isSecond(String JavaDoc s) {
741         if (isEmpty(s)) return defaultEmptyOK;
742         return isIntegerInRange(s, 0, 59);
743     }
744
745     /** isDate returns true if string arguments year, month, and day form a valid date. */
746     public static boolean isDate(String JavaDoc year, String JavaDoc month, String JavaDoc day) {
747         // catch invalid years(not 2- or 4-digit) and invalid months and days.
748
if (!(isYear(year) && isMonth(month) && isDay(day))) return false;
749
750         int intYear = Integer.parseInt(year);
751         int intMonth = Integer.parseInt(month);
752         int intDay = Integer.parseInt(day);
753
754         // catch invalid days, except for February
755
if (intDay > daysInMonth[intMonth - 1]) return false;
756         if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;
757         return true;
758     }
759
760     /** isDate returns true if string argument date forms a valid date. */
761     public static boolean isDate(String JavaDoc date) {
762         if (isEmpty(date)) return defaultEmptyOK;
763         String JavaDoc month;
764         String JavaDoc day;
765         String JavaDoc year;
766
767         int dateSlash1 = date.indexOf("/");
768         int dateSlash2 = date.lastIndexOf("/");
769
770         if (dateSlash1 <= 0 || dateSlash1 == dateSlash2) return false;
771         month = date.substring(0, dateSlash1);
772         day = date.substring(dateSlash1 + 1, dateSlash2);
773         year = date.substring(dateSlash2 + 1);
774
775         return isDate(year, month, day);
776     }
777
778     /** isDate returns true if string argument date forms a valid date and is after today. */
779     public static boolean isDateAfterToday(String JavaDoc date) {
780         if (isEmpty(date)) return defaultEmptyOK;
781         int dateSlash1 = date.indexOf("/");
782         int dateSlash2 = date.lastIndexOf("/");
783
784         if (dateSlash1 <= 0) return false;
785
786         java.util.Date JavaDoc passed = null;
787         if (dateSlash1 == dateSlash2) {
788             // consider the day to be optional; use the first day of the following month for comparison since this is an is after test
789
String JavaDoc month = date.substring(0, dateSlash1);
790             String JavaDoc day = "28";
791             String JavaDoc year = date.substring(dateSlash1 + 1);
792             if (!isDate(year, month, day)) return false;
793
794             try {
795                 int monthInt = Integer.parseInt(month);
796                 int yearInt = Integer.parseInt(year);
797                 Calendar JavaDoc calendar = Calendar.getInstance();
798                 calendar.set(yearInt, monthInt - 1, 0, 0, 0, 0);
799                 calendar.add(Calendar.MONTH, 1);
800                 passed = new java.util.Date JavaDoc(calendar.getTime().getTime());
801             } catch (Exception JavaDoc e) {
802                 passed = null;
803             }
804         } else {
805             String JavaDoc month = date.substring(0, dateSlash1);
806             String JavaDoc day = date.substring(dateSlash1 + 1, dateSlash2);
807             String JavaDoc year = date.substring(dateSlash2 + 1);
808             if (!isDate(year, month, day)) return false;
809             passed = UtilDateTime.toDate(month, day, year, "0", "0", "0");
810         }
811
812         java.util.Date JavaDoc now = UtilDateTime.nowDate();
813         if (passed != null) {
814             return passed.after(now);
815         } else {
816             return false;
817         }
818     }
819
820     /** isTime returns true if string arguments hour, minute, and second form a valid time. */
821     public static boolean isTime(String JavaDoc hour, String JavaDoc minute, String JavaDoc second) {
822         // catch invalid years(not 2- or 4-digit) and invalid months and days.
823
if (isHour(hour) && isMinute(minute) && isSecond(second))
824             return true;
825         else
826             return false;
827     }
828
829     /** isTime returns true if string argument time forms a valid time. */
830     public static boolean isTime(String JavaDoc time) {
831         if (isEmpty(time)) return defaultEmptyOK;
832
833         String JavaDoc hour;
834         String JavaDoc minute;
835         String JavaDoc second;
836
837         int timeColon1 = time.indexOf(":");
838         int timeColon2 = time.lastIndexOf(":");
839
840         if (timeColon1 <= 0) return false;
841         hour = time.substring(0, timeColon1);
842         if (timeColon1 == timeColon2) {
843             minute = time.substring(timeColon1 + 1);
844             second = "0";
845         } else {
846             minute = time.substring(timeColon1 + 1, timeColon2);
847             second = time.substring(timeColon2 + 1);
848         }
849         return isTime(hour, minute, second);
850     }
851
852     /** Checks credit card number with Luhn Mod-10 test
853      *
854      * @param stPassed a string representing a credit card number
855      * @return true, if the credit card number passes the Luhn Mod-10 test, false otherwise
856      */

857     public static boolean isCreditCard(String JavaDoc stPassed) {
858         if (isEmpty(stPassed)) return defaultEmptyOK;
859         String JavaDoc st = stripCharsInBag(stPassed, creditCardDelimiters);
860
861         int sum = 0;
862         int mul = 1;
863         int l = st.length();
864
865         // Encoding only works on cards with less than 19 digits
866
if (l > 19) return (false);
867         for (int i = 0; i < l; i++) {
868             String JavaDoc digit = st.substring(l - i - 1, l - i);
869             int tproduct = 0;
870
871             try {
872                 tproduct = Integer.parseInt(digit, 10) * mul;
873             } catch (Exception JavaDoc e) {
874                 Debug.logWarning(e.getMessage());
875                 return false;
876             }
877             if (tproduct >= 10)
878                 sum += (tproduct % 10) + 1;
879             else
880                 sum += tproduct;
881             if (mul == 1)
882                 mul++;
883             else
884                 mul--;
885         }
886         // Uncomment the following line to help create credit card numbers
887
// 1. Create a dummy number with a 0 as the last digit
888
// 2. Examine the sum written out
889
// 3. Replace the last digit with the difference between the sum and
890
// the next multiple of 10.
891

892         // document.writeln("<BR>Sum = ",sum,"<BR>");
893
// alert("Sum = " + sum);
894

895         if ((sum % 10) == 0)
896             return true;
897         else
898             return false;
899     }
900
901     /** Checks to see if the cc number is a valid Visa number
902      *
903      * @param cc a string representing a credit card number; Sample number: 4111 1111 1111 1111(16 digits)
904      * @return true, if the credit card number is a valid VISA number, false otherwise
905      */

906     public static boolean isVisa(String JavaDoc cc) {
907         if (((cc.length() == 16) || (cc.length() == 13)) && (cc.substring(0, 1).equals("4")))
908             return isCreditCard(cc);
909         return false;
910     }
911
912     /** Checks to see if the cc number is a valid Master Card number
913      *
914      * @param cc a string representing a credit card number; Sample number: 5500 0000 0000 0004(16 digits)
915      * @return true, if the credit card number is a valid MasterCard number, false otherwise
916      */

917     public static boolean isMasterCard(String JavaDoc cc) {
918         int firstdig = Integer.parseInt(cc.substring(0, 1));
919         int seconddig = Integer.parseInt(cc.substring(1, 2));
920
921         if ((cc.length() == 16) && (firstdig == 5) && ((seconddig >= 1) && (seconddig <= 5)))
922             return isCreditCard(cc);
923         return false;
924
925     }
926
927     /** Checks to see if the cc number is a valid American Express number
928      * @param cc - a string representing a credit card number; Sample number: 340000000000009(15 digits)
929      * @return true, if the credit card number is a valid American Express number, false otherwise
930      */

931     public static boolean isAmericanExpress(String JavaDoc cc) {
932         int firstdig = Integer.parseInt(cc.substring(0, 1));
933         int seconddig = Integer.parseInt(cc.substring(1, 2));
934
935         if ((cc.length() == 15) && (firstdig == 3) && ((seconddig == 4) || (seconddig == 7)))
936             return isCreditCard(cc);
937         return false;
938
939     }
940
941     /** Checks to see if the cc number is a valid Diners Club number
942      * @param cc - a string representing a credit card number; Sample number: 30000000000004(14 digits)
943      * @return true, if the credit card number is a valid Diner's Club number, false otherwise
944      */

945     public static boolean isDinersClub(String JavaDoc cc) {
946         int firstdig = Integer.parseInt(cc.substring(0, 1));
947         int seconddig = Integer.parseInt(cc.substring(1, 2));
948
949         if ((cc.length() == 14) && (firstdig == 3) && ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
950             return isCreditCard(cc);
951         return false;
952     }
953
954     /** Checks to see if the cc number is a valid Carte Blanche number
955      * @param cc - a string representing a credit card number; Sample number: 30000000000004(14 digits)
956      * @return true, if the credit card number is a valid Carte Blanche number, false otherwise
957      */

958     public static boolean isCarteBlanche(String JavaDoc cc) {
959         return isDinersClub(cc);
960     }
961
962     /** Checks to see if the cc number is a valid Discover number
963      * @param cc - a string representing a credit card number; Sample number: 6011000000000004(16 digits)
964      * @return true, if the credit card number is a valid Discover card number, false otherwise
965      */

966     public static boolean isDiscover(String JavaDoc cc) {
967         String JavaDoc first4digs = cc.substring(0, 4);
968
969         if ((cc.length() == 16) && (first4digs.equals("6011")))
970             return isCreditCard(cc);
971         return false;
972     }
973
974     /** Checks to see if the cc number is a valid EnRoute number
975      * @param cc - a string representing a credit card number; Sample number: 201400000000009(15 digits)
976      * @return true, if the credit card number is a valid enRoute card number, false, otherwise
977      */

978     public static boolean isEnRoute(String JavaDoc cc) {
979         String JavaDoc first4digs = cc.substring(0, 4);
980
981         if ((cc.length() == 15) && (first4digs.equals("2014") || first4digs.equals("2149")))
982             return isCreditCard(cc);
983         return false;
984     }
985
986     /** Checks to see if the cc number is a valid JCB number
987      * @param cc - a string representing a credit card number; Sample number: 3088000000000009(16 digits)
988      * @return true, if the credit card number is a valid JCB card number, false otherwise
989      */

990     public static boolean isJCB(String JavaDoc cc) {
991         String JavaDoc first4digs = cc.substring(0, 4);
992
993         if ((cc.length() == 16) &&
994             (first4digs.equals("3088") ||
995                 first4digs.equals("3096") ||
996                 first4digs.equals("3112") ||
997                 first4digs.equals("3158") ||
998                 first4digs.equals("3337") ||
999                 first4digs.equals("3528")))
1000            return isCreditCard(cc);
1001        return false;
1002    }
1003
1004    /** Checks to see if the cc number is a valid number for any accepted credit card
1005     * @param ccPassed - a string representing a credit card number
1006     * @return true, if the credit card number is any valid credit card number for any of the accepted card types, false otherwise
1007     */

1008    public static boolean isAnyCard(String JavaDoc ccPassed) {
1009        if (isEmpty(ccPassed)) return defaultEmptyOK;
1010
1011        String JavaDoc cc = stripCharsInBag(ccPassed, creditCardDelimiters);
1012
1013        if (!isCreditCard(cc)) return false;
1014        if (isMasterCard(cc) || isVisa(cc) || isAmericanExpress(cc) || isDinersClub(cc) ||
1015                isDiscover(cc) || isEnRoute(cc) || isJCB(cc))
1016            return true;
1017        return false;
1018    }
1019
1020    /** Checks to see if the cc number is a valid number for any accepted credit card, and return the name of that type
1021     * @param ccPassed - a string representing a credit card number
1022     * @return true, if the credit card number is any valid credit card number for any of the accepted card types, false otherwise
1023     */

1024    public static String JavaDoc getCardType(String JavaDoc ccPassed) {
1025        if (isEmpty(ccPassed)) return "Unknown";
1026        String JavaDoc cc = stripCharsInBag(ccPassed, creditCardDelimiters);
1027
1028        if (!isCreditCard(cc)) return "Unknown";
1029
1030        if (isMasterCard(cc)) return "MasterCard";
1031        if (isVisa(cc)) return "Visa";
1032        if (isAmericanExpress(cc)) return "AmericanExpress";
1033        if (isDinersClub(cc)) return "DinersClub";
1034        if (isDiscover(cc)) return "Discover";
1035        if (isEnRoute(cc)) return "EnRoute";
1036        if (isJCB(cc)) return "JCB";
1037        return "Unknown";
1038    }
1039
1040    /** Checks to see if the cc number is a valid number for the specified type
1041     * @param cardType - a string representing the credit card type
1042     * @param cardNumberPassed - a string representing a credit card number
1043     * @return true, if the credit card number is valid for the particular credit card type given in "cardType", false otherwise
1044     */

1045    public static boolean isCardMatch(String JavaDoc cardType, String JavaDoc cardNumberPassed) {
1046        if (isEmpty(cardType)) return defaultEmptyOK;
1047        if (isEmpty(cardNumberPassed)) return defaultEmptyOK;
1048        String JavaDoc cardNumber = stripCharsInBag(cardNumberPassed, creditCardDelimiters);
1049
1050        if ((cardType.equalsIgnoreCase("VISA")) && (isVisa(cardNumber))) return true;
1051        if ((cardType.equalsIgnoreCase("MASTERCARD")) && (isMasterCard(cardNumber))) return true;
1052        if (((cardType.equalsIgnoreCase("AMERICANEXPRESS")) || (cardType.equalsIgnoreCase("AMEX"))) && (isAmericanExpress(cardNumber))) return true;
1053        if ((cardType.equalsIgnoreCase("DISCOVER")) && (isDiscover(cardNumber))) return true;
1054        if ((cardType.equalsIgnoreCase("JCB")) && (isJCB(cardNumber))) return true;
1055        if (((cardType.equalsIgnoreCase("DINERSCLUB")) || (cardType.equalsIgnoreCase("DINERS"))) && (isDinersClub(cardNumber))) return true;
1056        if ((cardType.equalsIgnoreCase("CARTEBLANCHE")) && (isCarteBlanche(cardNumber))) return true;
1057        if ((cardType.equalsIgnoreCase("ENROUTE")) && (isEnRoute(cardNumber))) return true;
1058        return false;
1059    }
1060
1061
1062    /** isNotPoBox returns true if address argument does not contain anything that looks like a a PO Box. */
1063    public static boolean isNotPoBox(String JavaDoc s) {
1064        if (isEmpty(s)) return defaultEmptyOK;
1065
1066        // strings to check from Greg's program
1067
// "P.O. B"
1068
// "P.o.B"
1069
// "P.O B"
1070
// "PO. B"
1071
// "P O B"
1072
// "PO B"
1073
// "P.0. B"
1074
// "P0 B"
1075

1076        String JavaDoc sl = s.toLowerCase();
1077        if (sl.indexOf("p.o. b") != -1) return false;
1078        if (sl.indexOf("p.o.b") != -1) return false;
1079        if (sl.indexOf("p.o b") != -1) return false;
1080        if (sl.indexOf("p o b") != -1) return false;
1081        if (sl.indexOf("po b") != -1) return false;
1082        if (sl.indexOf("pobox") != -1) return false;
1083        if (sl.indexOf("po#") != -1) return false;
1084        if (sl.indexOf("po #") != -1) return false;
1085
1086        // now with 0's for them sneaky folks
1087
if (sl.indexOf("p.0. b") != -1) return false;
1088        if (sl.indexOf("p.0.b") != -1) return false;
1089        if (sl.indexOf("p.0 b") != -1) return false;
1090        if (sl.indexOf("p 0 b") != -1) return false;
1091        if (sl.indexOf("p0 b") != -1) return false;
1092        if (sl.indexOf("p0box") != -1) return false;
1093        if (sl.indexOf("p0#") != -1) return false;
1094        if (sl.indexOf("p0 #") != -1) return false;
1095        return true;
1096    }
1097}
1098
Popular Tags