工具类-校验

本文介绍了一套实用的正则表达式验证方法,包括手机号、身份证号、纯数字、数字字母组合等多种常见格式的校验逻辑。这些方法适用于各种应用场景,帮助开发者确保输入数据的准确性和合规性。
/*
 * 手机效验
 * 正确 true
 * 错误 false
 */
public boolean isMobile(String mobiles) {

	Pattern p = Pattern.compile("^1[3|4|5|7|8]\\d{9}$");
	Matcher m = p.matcher(mobiles);
	return m.matches();

}

/*
 * 手机格式校验(11位)
 * 正确 true
 * 错误 false
 */
public boolean isPhone(String mobiles) {

	Pattern p = Pattern.compile("1[3|5|7|8|][0-9]{9}");
	Matcher m = p.matcher(mobiles);
	return m.matches();

}

/*
 * 纯数字效验	
 * 纯数字 true
 * 非纯数字 false
 */
 public boolean isNumber(String str)
	{
		java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("[0-9]*");
		java.util.regex.Matcher match=pattern.matcher(str);
		return match.matches();
	}


 /*
 *  数字字母效验
 *  通过 true 
 *  不通过 false
 */
public boolean isNumberLetter(String str) {
	if (Pattern.matches("^[0-9A-Za-z]{8,16}$", str)) {    
		return true;
	} else {
		return false;
	}
}

/*
 *  只能输入汉字,长度不限
 *  通过 true 
 *  不通过 false
 */
public boolean ischinese(String str) {
	if (Pattern.matches("^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$", str)) {        
		return true;
	} else {
		return false;
	}
}

/*
 *  密码英文数字
 *  通过 true 
 *  不通过 false
 */
public boolean isPassword(String str) {
	if (Pattern.matches("[A-Za-z0-9]+", str)) { 
		return true;
	} else {
		return false;
	}
}
	
/**
 * 身份证编码校验
 * @param idCard 校验身份证对象
 * @return  不合法:true 合法:false
 */
public boolean isIdCardCheck(String idCard) {
	if (!StringUtils.isEmpty(idCard) && Pattern.matches("\\d{15}|\\d{18}",idCard)) {
		return true;
	}
	return false;
}


Hibernate Validator 是一个基于 JSR 380 规范实现的校验框架,它提供了一系列的注解和 API,方便我们对 Java 对象进行校验。下面给出一个 Hibernate Validator 校验工具类的示例: ```java public class ValidationUtils { private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); /** * 校验对象 * @param object 待校验对象 * @param groups 待校验的组 * @throws ValidationException 校验不通过,则报ValidationException异常 */ public static void validateEntity(Object object, Class<?>... groups) throws ValidationException { Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); if (!constraintViolations.isEmpty()) { StringBuilder msg = new StringBuilder(); for (ConstraintViolation<Object> constraintViolation : constraintViolations) { msg.append(constraintViolation.getMessage()).append(";"); } throw new ValidationException(msg.toString()); } } } ``` 上述代码定义了一个名为 ValidationUtils 的工具类,其中包含了一个名为 validateEntity 的静态方法。该方法接收两个参数,其中 object 表示待校验的对象,groups 表示校验分组。方法内部使用 Hibernate Validator 的 API 进行校验,并将校验结果保存在 constraintViolations 集合中。如果集合不为空,则表示校验不通过,将所有错误消息拼接起来,并抛出 ValidationException 异常。如果集合为空,则表示校验通过,方法直接返回。 可以看出,使用 Hibernate Validator 编写校验工具类非常简单,只需要创建一个 Validator 对象并调用其 validate 方法即可。对于校验不通过的情况,可以将所有错误消息拼接起来,或者只取第一个错误消息作为异常消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值