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

Java中正则表达式验证

2012-08-22 10:03 309 查看
/**
* 验证数据的合法性
* @param map
* @return
*/
public static String checkAllComponent(Map<String, String> map) {
// 登陆用户名,*(3~16位字母、数字和下划线的任意组合
String regx = "^[a-zA-Z0-9_]{1}([a-zA-Z0-9]|[_]){2,16}$";
if (!checkValue(regx, map.get("userId"))) {
return Utils.USER_ERROR;
}

// 修改用户的时候,6~16位字母、数字、特殊符号的组合)
if (map.get("chpass") != null && "1".equals(map.get("chpass"))) {
if (!map.get("newPass").equals(map.get("renewPass"))) {
return Utils.PASSWORD_ERROR1;
} else {
if (map.get("newPass").length() <6 || map.get("newPass").length() > 16) {
return Utils.PASSWORD_ERROR2;
}
}
} else if (map.get("chpass") == null) {
// 添加用户,密码验证
if (!map.get("password").equals(map.get("repassword"))) {
return Utils.PASSWORD_ERROR1;
} else {
if (map.get("password").length() < 6 || map.get("password").length() > 16) {
return Utils.PASSWORD_ERROR2;
}
}
}

// 角色验证,至少选择一种角色
if ("0".equals(map.get("role"))) {
return Utils.ROLE_ERROR;
}

// 验证个人信息,16个字母,4个汉字
if (map.get("userName") != null && !"".equals(map.get("userName"))) {
// 验证英文姓名16个字节
regx = "^\\w+[\\w\\s]+\\w+$";
boolean english = checkValue(regx, map.get("userName").trim());
// 验证中文姓名,4个汉字
regx = "^[\u4e00-\u9fa5]{1,4}$";
boolean chinese = checkValue(regx, map.get("userName").trim());
if (!(english || chinese)) {
return Utils.USERNAME_ERROR;
}
}

if (map.get("mobile") != null && !"".equals(map.get("mobile"))) {
// 验证电话
regx = "^[+]{0,1}(\\d){1,3}([-]?((\\d)){1,12})+$";
if (!checkValue(regx, map.get("mobile"))) {
return Utils.MOBILE_ERROR;
}
}

if (map.get("email")!= null && !"".equals(map.get("email"))) {
// 验证邮箱
regx = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$";
if (!checkValue(regx, map.get("email"))) {
return Utils.EMAIL_ERROR;
}
}

return null;
}


/**
* 提交之前验证输入是否合法
*/
public static boolean checkValue(String regx, String checkValue){
// 用户名是否合法:3~16位字母、数字和下划线的任意组合
Pattern pattern  = Pattern.compile(regx);
Matcher matcher = pattern.matcher(checkValue);
boolean b = matcher.matches();
return b;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: