您的位置:首页 > 编程语言 > Java开发

java中几种后台验证小例子(日期、Email、电话等)

2012-11-08 17:59 627 查看
本例子是本人在开发项目是所用到的一些后台验证的小工具。

 public static final Log log = LogFactory.getLog(Utils.class);

 //数字的正则表达式

 public static final String REGEX_DIGIT = "[0-9]+";

  // 手机号正则表达式

 public static final String REGEX_MOBILE = "1[358][0-9]{9}";

  *//电子邮件的正则表达式

 public static final String REGEX_EMAIL = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

//匹配版本号为 数字用“.”分隔的形式

 public static final String VERSION = "[0-9.]+";

 

 // 日期:2010-01-02正则表达式

 public static final String CHECK_SHORTDATE="^((\\d{2}(([02468][048])|([13579][26]))[\\-\\-\\s]?((" +

   "((0?" +"[13578])|(1[02]))[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))" +"|(((0?[469])|" +

   "(11))[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(30)))|" +"(0?2[\\-\\-\\s]?((0?[1-9])|" +

   "([1-2][0-9])))))|(\\d{2}(([02468][12" +"35679])|([13579][01345789]))" +

   "[\\-\\-\\s]?((((0?[13578])|(1[02]))" +"[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))" +

   "|(((0?[469])|(11))" +"[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\-\\s]?((0?[" +"1-9])|(1[0-9])|(2[0-8]))))))";

 //日期:2012-02-29 23:59:59

 public static final String CHECK_LONGDATE="^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])" +

   "|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|" +

   "([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579]" +

   "[01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|" +

   "(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|" +

   "(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";

 /**

  * 过滤null

  *

  * @param str

  * @return

  */

 public static String escNull(String str) {

  if (str == null) {

   return "";

  }

  if ("null".equals(str)) {

   return "";

  }

  return str;

 }

 /**

  * 非空判断 true-非空

  *

  * @param key

  * @return

  */

 public static boolean nn(String key) {

  if (!"".equals(escNull(key))) {

   return true;

  }

  return false;

 }

 public static boolean nn(Object key) {

  if (key != null) {

   return true;

  }

  return false;

 }

 /**

  * 空串或空

  *

  * @param key

  * @return 为空则true

  */

 public static boolean n(String key) {

  if ("".equals(escNull(key))) {

   return true;

  }

  return false;

 }

 // String转换成int类型

 public static boolean StringByInt(String name) {

  if (name == "" || "".equals(name) || name == null) {

   return false;

  } else {

   Integer.parseInt(name);

   return true;

  }

 }

 public static boolean n(Object key) {

  if (key == null) {

   return true;

  }

  return false;

 }

 /**

  * 数字字符串判断

  *

  * @param s

  * @return

  */

 public static boolean digit(String s) {

  if("".endsWith(s)){

   return true;

  }else{

   Pattern p = Pattern.compile(REGEX_DIGIT);

   Matcher m = p.matcher(s);

   if (m.matches()) {

    return true;

   }

   return false;

  }

 }

 /**

  * 手机号验证

  *

  * @param mobile

  * @return

  */

 public static boolean mobile(String mobile) {

  if("".equals(mobile)|| mobile==""){

   return true;

  }else{

   if (n(mobile)) {

    return false;

   }

   if (mobile.length() < 11) {

    return false;

   }

   if (mobile.matches(REGEX_MOBILE)) {

    return true;

   }

  return false;

  }

 }

 /**

  * email验证

  *

  * @param email

  * @return

  */

 public static boolean email(String email) {

  if (n(email)) {

   return false;

  }

  if (email.length() < 11) {

   return false;

  }

  if (email.matches(REGEX_EMAIL)) {

   return true;

  }

  return false;

 }

 /**

  * 加密

  *

  * @param src

  * @return

  */

 public static String md5(String src) {

  byte[] bytes = src.getBytes();

  MessageDigest md = null;

  try {

   md = MessageDigest.getInstance("MD5");

  } catch (Exception e) {

   log.error(e);

   return src;

  }

  md.reset();

  md.update(bytes);

  byte[] encodedPassword = md.digest();

  StringBuffer buf = new StringBuffer();

  for (byte abit : encodedPassword) {

   if ((abit & 0xff) < 0x10) {

    buf.append("0");

   }

   buf.append(Long.toString(abit & 0xff, 16));

  }

  return buf.toString();

 }

 /**

  * 数字字符串转化为数字

  *

  * return -1则表示非数字字符串

  */

 public static int toInt(String value) {

  if (n(value)) {

   return -1;

  }

  if (!value.matches(REGEX_DIGIT)) {

   return -1;

  }

  return Integer.parseInt(value);

 }

 /**

  * 带参消息格式化

  */

 public static String mf(String pattern, Object[] arguments) {

  if (Utils.n(pattern) || Utils.n(arguments)) {

   return "";

  }

  return MessageFormat.format(pattern, arguments);

 }

 /**

  * UUID码

  */

 public static String UUID() {

  UUID uuid = UUID.randomUUID();

  String id = uuid.toString();

  return id.replaceAll("-", "");

 }

 public static String token() {

  return GUID.generateGUID();

 }

 public static String tokenSecret(String token) {

  return md5(token);

 }

 /**

  * 印面打印值

  */

 public static PrintWriter printOut() {

  HttpServletResponse response = ServletActionContext.getResponse();

  PrintWriter out;

  response.setHeader("Cache-Control", "no-cache");

  response.setContentType("text/json;charset=utf-8");

  // response.setContentType("text/html;charset=utf-8");

  try {

   out = response.getWriter();

   return out;

  } catch (IOException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

  return null;

 }

 /**

  * 印刷号做加法运算

  */

 public static String addPrintNum(String printNum, String count) {

  char[] printNumArray = printNum.toCharArray();

  int index = 0;

  String indeStr = "";

  for (int i = 0; i < printNumArray.length; i++) {

   if (printNumArray[i] == '0') {

    index++;

    indeStr = indeStr + "0";

   } else {

    break;

   }

  }

  String printNumSub = "";

  if (index == 0) {

   printNumSub = printNum;

  } else {

   printNumSub = printNum.substring(index, printNum.length());

  }

  BigDecimal a = new BigDecimal(printNumSub);

  BigDecimal b = new BigDecimal(count);

  BigDecimal c = a.add(b);

  return indeStr + c.toString();

 }

 /**

  * 印刷号做减法运算

  */

 public static String subtractPrintNum(String printNum, String count) {

  BigDecimal a = new BigDecimal(printNum);

  BigDecimal b = new BigDecimal(count);

  BigDecimal c = b.subtract(a);

  return c.toString();

 }

 /**

  * 生成随机的八位防伪码

  */

 public static String getSercurCode() {

  java.util.Random r = new java.util.Random();

  String randomStr = String.valueOf(r.nextInt(100000000));

  if (randomStr.length() < 8) {

   randomStr = "0" + randomStr;

  }

  return randomStr;

 }

 /**

  * 两个时间比较大小 2012-08-14 15:13:54

  */

 @SuppressWarnings("unused")

 public static boolean compareDate(String date) {

  java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(

    "yyyy-MM-dd HH:mm:ss");

  java.util.Date Now = new java.util.Date();

  String nowtime = formatter.format(Now);

  try {

   // 把起飞时间转换成毫秒

   long filght = formatter.parse(date).getTime();

   // 把当前时间转换成毫秒

   long nowdate = formatter.parse(nowtime).getTime();

   // 起飞时间超过退保此时时间(能退保)

   if (filght > nowdate) {

    return false;

   }

   // 退保时间超过起飞时间(不能退保)

   else {

    return true;

   }

  } catch (ParseException e) {

   e.printStackTrace();

  }

  return false;

 }

 /**

  * 如果有多个航班号的话 使用这个方法生成电子保单号 也就是依次往下递加的 (团体和个人画面都需要)

  *

  * @param str

  * @param size

  * @return

  */

 public static String getBDH(String str, int size) {

  int cutLast = Integer.parseInt(str.substring(str.length() - 2, str

    .length()));

  // 如果最后2位到10 那么就截取成0了 就不对了 就成了从25以后不再累加了

  if (cutLast > 9) {

   cutLast = Integer.parseInt(str.substring(str.length() - 2, str

     .length()));

   int invo = cutLast + size;

   return str.substring(0, str.length() - 2) + invo;

  } else {

   int invo = cutLast + size;

   return str.substring(0, str.length() - 2) + "0" + invo;

  }

 }

 /**

  * 判断一个字符串中是否包含中文

  *

  * @param args

  */

 public static final boolean isChinese(String strName) {

  char[] ch = strName.toCharArray();

  for (int i = 0; i < ch.length; i++) {

   char c = ch[i];

   // 调用把字符串转化为字符来比较的方法isChinese

   if (CharChinese(c)) {

    return false;

   }

  }

  return true;

 }

 // 分解字符串为字节,经行判断

 private static final boolean CharChinese(char c) {

  Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

  if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS

    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS

    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

    || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION

    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION

    || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {

   return true;

  }

  return false;

 }

 // 判断字符串长度是否大于7

 /*

  * public static boolean chekcStringThree(String str){ if(str.length()>7){

  * return false; } else{ return true; } } //判断字符串长度是否大于10 public static

  * boolean chekcStringLenth(String str){ if(str.length()>10){ return false; }

  * else{ return true; } }

  *

  *

  * //判断字符串长度是否大于32 public static boolean chekcStrLenthS(String str){

  * if(str.length()>32){ return false; } else{ return true; } }

  * //判断字符串长度是否大于64 public static boolean chekcStrLenth(String str){

  * if(str.length()>64){ return false; } else{ return true; } }

  * //判断字符串长度是否大于200 public static boolean chekcStrLenthT(String str){

  * if(str.length()>200){ return false; } else{ return true; } }

  * //判断字符串长度是否大于1000 public static boolean chekcStrLenthO(String str){

  * if(str.length()>1000){ return false; } else{ return true; } }

  */

 // 判断字符串长度。str传入过来的字符串,length长度参数。

 public static boolean chekcStrLength(String str, Integer length) {

  if (str.length() > length) {

   return false;

  }

  else if(isSpecialChar(str)){

   return false;

  }

  else {

   return true;

  }

 }

 // 判断字符串是否有空格。有返回false,无返回true

 public static boolean isBlank(String str) {

  boolean b = str.endsWith(" ");

  if (b) {

   return false;

  } else {

   return true;

  }

 }

 

 //判断selected值存在

 public static boolean validateOption(Object[] options, Object value) {

  boolean isValidValue = false;

  try {

   List list = Arrays.asList(options);

   if (list != null) {

    isValidValue = list.contains(value);

   }

  } catch (Exception e) {

  }

  return isValidValue;

 }

 //判断一个字符串是否是double类型

 public static boolean   isDouble(String   str)

 { 

  boolean isdouble=false;

       try{

        Double.parseDouble(str);

        isdouble=true;

           } catch(Exception e){

            isdouble=false;

           }

       return   isdouble;

 }

 //验证一个字符串是否是int类型

 public static boolean isInt(String str){

  boolean isFieldValid=false;

  try{

   Integer.parseInt(str);

   isFieldValid = true;

  }catch(Exception e){

   isFieldValid=false;

  }

  return isFieldValid;

 }

 /**

  * 验证日期如:2010-10-05

  * @param args

  */

 public static boolean checkShortDate(String str){

  Pattern p = Pattern.compile(CHECK_SHORTDATE);

  Boolean b= p.matcher(str).matches();

  if(b){

   return true;

  }else{

   return false;

  }

 }

 /**

  * 验证日期如:2012-02-29 23:59:59

  * @param args

  */

 public static boolean checkLongDate(String str){

  Pattern p = Pattern.compile(CHECK_LONGDATE);

  Boolean b= p.matcher(str).matches();

  if(b){

   return true;

  }else{

   return false;

  }

 }

 /**

  * 判断字符串是否包含特殊字符

  * 如果有非法

  * 可以包括"."

   * isSpecialChar 方法

   * <p>方法说明:</p>

   * @param str

   * @return

   * @return boolean

   * @author gaoy

   * @date 2012-10-23

  */

 public static boolean isSpecialChar(String str){

  String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"; 

  Pattern   p   =   Pattern.compile(regEx);    

  Matcher   m   =   p.matcher(str); 

  return m.find();

 }

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: