⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 utilvalidate.java

📁 短信发送
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
package com.jdev.util;import java.util.Calendar;import java.util.Collection;/** * <p>General input/data validation methods * <p>Utility methods for validating data, especially input. See detailed description below. * * @author     <a href="mailto:jonesde@ofbiz.org">David E. Jones</a> * @created    May 21, 2001 * @version    1.0 * * * <br> SUMMARY * <br> * <br> This is a set of meethods for validating input. Functions are provided to validate: * <br>    - U.S. and international phone/fax numbers * <br>    - U.S. ZIP codes(5 or 9 digit postal codes) * <br>    - U.S. Postal Codes(2 letter abbreviations for names of states) * <br>    - U.S. Social Security Numbers(abbreviated as SSNs) * <br>    - email addresses * <br>	   - dates(entry of year, month, and day and validity of combined date) * <br>	   - credit card numbers * <br> * <br> Supporting utility functions validate that: * <br>    - characters are Letter, Digit, or LetterOrDigit * <br>    - strings are a Signed, Positive, Negative, Nonpositive, or Nonnegative integer * <br>    - strings are a Float or a SignedFloat * <br>    - strings are Alphabetic, Alphanumeric, or Whitespace * <br>    - strings contain an integer within a specified range * <br> * <br> Other utility functions are provided to: * <br>    - remove from a string characters which are/are not in a "bag" of selected characters * <br>	   - strip whitespace/leading whitespace from a string * <br> * <br> ================================================================ * <br> NOTE: This code was adapted from the Netscape JavaScript form validation code, usually found in "FormChek.js". * <br> Credit card verification functions Originally included as Starter Application 1.0.0 in LivePayment. * <br> ================================================================ */public class UtilValidate {    /** boolean specifying by default whether or not it is okay for a String to be empty */    public static final boolean defaultEmptyOK = true;    /** digit characters */    public static final String digits = "0123456789";    /** lower-case letter characters */    public static final String lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";    /** upper-case letter characters */    public static final String uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";    /** letter characters */    public static final String letters = lowercaseLetters + uppercaseLetters;    /** whitespace characters */    public static final String whitespace = " \t\n\r";    /** decimal point character differs by language and culture */    public static final String decimalPointDelimiter = ".";    /** non-digit characters which are allowed in phone numbers */    public static final String phoneNumberDelimiters = "()- ";    /** characters which are allowed in US phone numbers */    public static final String validUSPhoneChars = digits + phoneNumberDelimiters;    /** characters which are allowed in international phone numbers(a leading + is OK) */    public static final String validWorldPhoneChars = digits + phoneNumberDelimiters + "+";    /** non-digit characters which are allowed in Social Security Numbers */    public static final String SSNDelimiters = "- ";    /** characters which are allowed in Social Security Numbers */    public static final String validSSNChars = digits + SSNDelimiters;    /** U.S. Social Security Numbers have 9 digits. They are formatted as 123-45-6789. */    public static final int digitsInSocialSecurityNumber = 9;    /** U.S. phone numbers have 10 digits. They are formatted as 123 456 7890 or(123) 456-7890. */    public static final int digitsInUSPhoneNumber = 10;    public static final int digitsInUSPhoneAreaCode = 3;    public static final int digitsInUSPhoneMainNumber = 7;    /** non-digit characters which are allowed in ZIP Codes */    public static final String ZipCodeDelimiters = "-";    /** our preferred delimiter for reformatting ZIP Codes */    public static final String ZipCodeDelimeter = "-";    /** characters which are allowed in Social Security Numbers */    public static final String validZipCodeChars = digits + ZipCodeDelimiters;    /** U.S. ZIP codes have 5 or 9 digits. They are formatted as 12345 or 12345-6789. */    public static final int digitsInZipCode1 = 5;    /** U.S. ZIP codes have 5 or 9 digits. They are formatted as 12345 or 12345-6789. */    public static final int digitsInZipCode2 = 9;    /** non-digit characters which are allowed in credit card numbers */    public static final String creditCardDelimiters = " -";    public static final String isNotEmptyMsg = "This field cannot be empty, please enter a value.";    public static final String isStateCodeMsg = "The State Code must be a valid two character U.S. state abbreviation(like CA for California).";    public static final String 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).";    public static final String isZipCodeMsg = "The ZIP Code must be a 5 or 9 digit U.S. ZIP Code(like 94043).";    public static final String isUSPhoneMsg = "The US Phone must be a 10 digit U.S. phone number(like 415-555-1212).";    public static final String isUSPhoneAreaCodeMsg = "The Phone Number Area Code must be 3 digits.";    public static final String isUSPhoneMainNumberMsg = "The Phone Number must be 7 digits.";    public static final String isContiguousZipCodeMsg = "Zip Code is not a valid Zip Code for one of the 48 contiguous United States .";    public static final String isInternationalPhoneNumberMsg = "The World Phone must be a valid international phone number.";    public static final String isSSNMsg = "The SSN must be a 9 digit U.S. social security number(like 123-45-6789).";    public static final String isEmailMsg = "The Email must be a valid email address(like john@email.com). Please re-enter it now.";    public static final String isAnyCardMsg = "The credit card number is not a valid card number.";    public static final String isCreditCardPrefixMsg = " is not a valid ";    public static final String isCreditCardSuffixMsg = " credit card number.";    public static final String isDayMsg = "The Day must be a day number between 1 and 31. ";    public static final String isMonthMsg = "The Month must be a month number between 1 and 12. ";    public static final String isYearMsg = "The Year must be a 2 or 4 digit year number. ";    public static final String isDatePrefixMsg = "The Day, Month, and Year for ";    public static final String isDateSuffixMsg = " do not form a valid date.  Please reenter them now.";    public static final String isHourMsg = "The Hour must be a number between 0 and 23.";    public static final String isMinuteMsg = "The Hour must be a number between 0 and 59.";    public static final String isSecondMsg = "The Hour must be a number between 0 and 59.";    public static final String isTimeMsg = "The Time must be a valid time formed like: HH:MM or HH:MM:SS.";    public static final String isDateMsg = "The Date must be a valid date formed like: MM/YY, MM/YYYY, MM/DD/YY, or MM/DD/YYYY.";    public static final String isDateAfterToday = "The Date must be a valid date after today, and formed like: MM/YY, MM/YYYY, MM/DD/YY, or MM/DD/YYYY.";    public static final String isIntegerMsg = "The Number must be a valid unsigned whole decimal number.";    public static final String isSignedIntegerMsg = "The Number must be a valid signed whole decimal number.";    public static final String isLongMsg = "The Number must be a valid unsigned whole decimal number.";    public static final String isSignedLongMsg = "The Number must be a valid signed whole decimal number.";    public static final String isFloatMsg = "The Number must be a valid unsigned decimal number.";    public static final String isSignedFloatMsg = "The Number must be a valid signed decimal number.";    public static final String isSignedDoubleMsg = "The Number must be a valid signed decimal number.";    /** An array of ints representing the number of days in each month of the year.     *  Note: February varies depending on the year */    public static final int[] daysInMonth = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};    /** Delimiter for USStateCodes String */    public static final String USStateCodeDelimiter = "|";    /** Valid U.S. Postal Codes for states, territories, armed forces, etc.     * See http://www.usps.gov/ncsc/lookups/abbr_state.txt. */    public static final String 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";    /** Valid contiguous U.S. postal codes */    public static final String 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";    public static boolean areEqual(Object obj, Object obj2) {        if (obj == null) {            return obj2 == null;        } else {            return obj.equals(obj2);        }    }    /** Check whether string s is empty. */    public static boolean isEmpty(String s) {        return ((s == null) || (s.length() == 0));    }    /** Check whether collection c is empty. */    public static boolean isEmpty(Collection c) {        return ((c == null) || (c.size() == 0));    }    /** Check whether string s is NOT empty. */    public static boolean isNotEmpty(String s) {        return ((s != null) && (s.length() > 0));    }    /** Check whether collection c is NOT empty. */    public static boolean isNotEmpty(Collection c) {        return ((c != null) && (c.size() > 0));    }    /** Returns true if string s is empty or whitespace characters only. */    public static boolean isWhitespace(String s) {        // Is s empty?        if (isEmpty(s)) return true;        // Search through string's characters one by one        // until we find a non-whitespace character.        // When we do, return false; if we don't, return true.        for (int i = 0; i < s.length(); i++) {            // Check that current character isn't whitespace.            char c = s.charAt(i);            if (whitespace.indexOf(c) == -1) return false;        }        // All characters are whitespace.        return true;    }    /** Removes all characters which appear in string bag from string s. */    public static String stripCharsInBag(String s, String bag) {        int i;        String returnString = "";        // Search through string's characters one by one.        // If character is not in bag, append to returnString.        for (i = 0; i < s.length(); i++) {            char c = s.charAt(i);            if (bag.indexOf(c) == -1) returnString += c;        }        return returnString;    }    /** Removes all characters which do NOT appear in string bag from string s. */    public static String stripCharsNotInBag(String s, String bag) {        int i;        String returnString = "";        // Search through string's characters one by one.        // If character is in bag, append to returnString.        for (i = 0; i < s.length(); i++) {            char c = s.charAt(i);            if (bag.indexOf(c) != -1) returnString += c;        }        return returnString;    }    /** Removes all whitespace characters from s.     *  Member whitespace(see above) defines which characters are considered whitespace. */    public static String stripWhitespace(String s) {        return stripCharsInBag(s, whitespace);    }    /** Returns true if single character c(actually a string) is contained within string s. */    public static boolean charInString(char c, String s) {        return (s.indexOf(c) != -1);        // for(int i = 0; i < s.length; i++) {        // if(s.charAt(i) == c) return true;        // }        // return false;    }    /** Removes initial(leading) whitespace characters from s.     *  Member whitespace(see above) defines which characters are considered whitespace. */    public static String stripInitialWhitespace(String s) {        int i = 0;        while ((i < s.length()) && charInString(s.charAt(i), whitespace)) i++;        return s.substring(i);        // return s.substring(i, s.length);    }    /** Returns true if character c is an English letter (A .. Z, a..z).     *     *  NOTE: Need i18n version to support European characters.     *  This could be tricky due to different character     *  sets and orderings for various languages and platforms. */    public static boolean isLetter(char c) {        return Character.isLetter(c);    }    /** Returns true if character c is a digit (0 .. 9). */    public static boolean isDigit(char c) {        return Character.isDigit(c);    }    /** Returns true if character c is a letter or digit. */    public static boolean isLetterOrDigit(char c) {        return Character.isLetterOrDigit(c);    }    /** Returns true if all characters in string s are numbers.     *     *  Accepts non-signed integers only. Does not accept floating     *  point, exponential notation, etc.     */    public static boolean isInteger(String s) {        if (isEmpty(s)) return defaultEmptyOK;        // Search through string's characters one by one        // until we find a non-numeric character.        // When we do, return false; if we don't, return true.        for (int i = 0; i < s.length(); i++) {            // Check that current character is number.            char c = s.charAt(i);            if (!isDigit(c)) return false;        }        // All characters are numbers.        return true;    }    /** Returns true if all characters are numbers;     *  first character is allowed to be + or - as well.     *     *  Does not accept floating point, exponential notation, etc.     */    public static boolean isSignedInteger(String s) {        if (isEmpty(s)) return defaultEmptyOK;        try {            int temp = Integer.parseInt(s);            return true;        } catch (Exception e) {            return false;        }        // int startPos = 0;        // boolean secondArg = defaultEmptyOK;        // if(isSignedInteger.arguments.length > 1) secondArg = isSignedInteger.arguments[1];        // skip leading + or -        // if((s.charAt(0) == "-") ||(s.charAt(0) == "+") ) startPos = 1;        // return(isInteger(s.substring(startPos, s.length), secondArg))    }    /** Returns true if all characters are numbers;     *  first character is allowed to be + or - as well.     *     *  Does not accept floating point, exponential notation, etc.     */    public static boolean isSignedLong(String s) {        if (isEmpty(s)) return defaultEmptyOK;        try {            long temp = Long.parseLong(s);            return true;        } catch (Exception e) {            return false;        }    }    /** Returns true if string s is an integer > 0. NOTE: using the Java Long object for greatest precision */    public static boolean isPositiveInteger(String s) {        if (isEmpty(s)) return defaultEmptyOK;        try {            long temp = Long.parseLong(s);            if (temp > 0) return true;            return false;        } catch (Exception e) {            return false;        }        // return(isSignedInteger(s, secondArg)        // &&((isEmpty(s) && secondArg)  ||(parseInt(s) > 0) ) );    }    /** Returns true if string s is an integer >= 0. */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -