java硬编码数据校验

使用注解校验可以达到无入侵方式校验。但是确灵活度不够。对于多参数关联校验,动态校验等情况则难以实现。

对于硬编码校验网上例子不多。硬编码校验可以采用链模式,显得灵活高效。

校验类如下

 
 
public class Assert {
//内部类
public static class ValidLink {
//校验错误信息保存
private String msg;

//获取错误结果
public String result() {
return msg;
}

//校验规则 是否相等
public ValidLink isEqual(Object a, Object b, String message) {
if (msg == null) {
if (!Objects.equals(a, b)) {
msg = message;
}
}
return this;
}

//校验规则是否为真
public ValidLink isTrue(boolean b, String message) {
if (msg == null) {
if (!b) {
msg = message;
}
}
return this;
}

}

//产生校验链
public static ValidLink validLink() {
return new ValidLink();
}
}
 

例子

        String msg= Assert.validLink()
                .rageLength(registrationNo, 1, 30, "工商注册号不能为空,且不能超过30个字符")
                .rageLength(name, 1, 63, "企业名称不能为空,且不能超过63个字符")
                .rageLength(registeredCapital, 1, 10, "注册资本不能为空,且不能超过10个字符")
                .isNumber(registeredCapital, "注册资本必须是数字")
                .inCollections(Arrays.asList("事业单位","国有控股企业","民营控股企业","外资投资企业"), companyType, true, "公司类型错误")
.isTrue(!companyType.equals("国有控股企业") || NumberUtils.gl(registeredCapital, 1000), "国企注册资本必须大于一千万") .rageLength(companyAddress
, 1, 100, "公司地址不能为空,且不能超过100个字符") .inCollections(Arrays.asList("独资", "多人控股"), shareStructure, "股份结构格式错误") .rageLength(registrationOrgan, 1, 30, "登记机关不能为空,且不能超过30个字符") .inCollections(BusyCache.getAllProvince().keySet(), registrationProvinces, "注册省份格式错误!") .isDate(establishedTime, "成立时间格式错误") .notNullMaxFile("企业资质证", businessLicenseImage, 10, null).result();

猜你喜欢

转载自www.cnblogs.com/nullAndValue/p/10041393.html
今日推荐