Spring表单验证

1. 内置表单验证

1.1 Bean Validator内置的注解

Annotation支持的数据类型作用Hibernate metadata impact
@AssertFalseBoolean, boolean判断关联属性是否为布尔值false没有@AssertTrue
@DecimalMaxBigDecimal, BigInteger, String, byte, short, int,long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number.被注解的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.没有
@DecimalMinBigDecimal, BigInteger, String, byte, short, int,long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number.被注解的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.没有
@Digits(integer=, fraction=)BigDecimal, BigInteger, String, byte, short, int,long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number.校验整数位数和小数位数对应的数据库表字段会被设置精度(precision)和准度(scale).
@Futurejava.util.Date, java.util.Calendar; Additionally supported by HV, if the Joda Time date/time API is on the class path: any implementations of ReadablePartial and ReadableInstant.检查给定的日期是否比现在晚.没有
@MaxBigDecimal, BigInteger, byte, short, int, longand the respective wrappers of the primitive types. Additionally supported by HV: String(the numeric value represented by a String is evaluated), any sub-type of Number.检查该值是否小于或等于约束条件中指定的最大值.会给对应的数据库表字段添加一个check的约束条件.
@MinBigDecimal, BigInteger, byte, short, int, longand the respective wrappers of the primitive types. Additionally supported by HV: String(the numeric value represented by a String is evaluated), any sub-type of Number.检查该值是否大于或等于约束条件中规定的最小值.会给对应的数据库表字段添加一个check的约束条件.
@NotNullAny typeChecks that the annotated value is notnull.对应的表字段不允许为null.
@NullAny typeChecks that the annotated value is null.没有
@Pastjava.util.Date, java.util.Calendar; Additionally supported by HV, if the Joda Time date/time API is on the class path: any implementations of ReadablePartial and ReadableInstant.检查注解对象中的值表示的日期比当前早.没有
@Pattern(regex=, flag=)String检查该字符串是否能够在match指定的情况下被regex定义的正则表达式匹配.没有
@Size(min=, max=)String, Collection, Map and arrays校验对象的size。本文作者认为前提是该对象有size()方法,String除外。对应的数据库表字段的长度会被设置成约束中定义的最大值.
@ValidAny non-primitive type递归的对关联对象进行校验, 如果关联对象是个集合或者数组, 那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.没有

1.2 Hibernate Validator拓展的注解

Annotation支持的数据类型作用Hibernate metadata impact
@CreditCardNumberString校验信用卡号码没有
@EmailString校验邮件地址没有
@Length(min=, max=)String功能同@Size,但是只支持String类型对应的数据库表字段的长度会被设置成约束中定义的最大值.
@NotBlankString不为null,不为空值,不为全空格。功能强大于@NotEmpty没有
@NotEmptyString,Collection,Map and arrays校验是否为null或者为空值。功能强于@NotNull没有
@Range(min=, max=)BigDecimal,BigInteger,String, byte,short, int,long and the respective wrappers of the primitive types判断数值的范围,不仅支持数值类型,还支持字符串、字节等等类型没有
@SafeHtml(whitelistType=, additionalTags=)CharSequence无使用价值没有
@ScriptAssert(lang=, script=, alias=)Any type无使用价值没有
@URL(protocol=, host=, port=, regexp=, flags=)StringChecks if the annotated string is a valid URL according to RFC2396. If any of the optional parameters protocol, host or port are specified, the corresponding URL fragments must match the specified values. The optional parametersregexp and flags allow to specify an additional regular expression (including regular expression flags) which the URL must match.没有

1.3. Validator框架拓展注解

Annotation支持的数据类型作用
@NotEmptyPatternString在字符串不为空的情况下,验证是否匹配正则表达式
@ListStringPatternList验证集合中的字符串是否满足正则表达式
@DateValidatorString验证日期格式是否满足正则表达式,Local为ENGLISH
@DateFormatCheckPatternString验证日期格式是否满足正则表达式,Local为自己手动指定

参考:Hibernate-validator校验框架


2. 自定义表单验证

例如在新增人员时,需要判断身份证号是否重复,若重复则提示已存在。

Validator提供了6个校验接口供开发人员使用:

  1. void validate(T object) throws Exception
    用途:校验一个对象的默认校验组的属性。
  2. void validate(T object, Class<?>… groups) throws Exception
    用途:校验一个对象的指定的一个或多个校验组的属性。
  3. void validateProperty(T object, String propertyName) throws Exception
    用途:校验一个对象的默认校验组的一个指定的属性值。
  4. void validateProperty(T object, String propertyName, Class<?>… groups) throws Exception
    用途:校验一个对象指定校验组中的一个指定的属性值。
  5. void validateValue(Class beanType, String propertyName, Object value) throws Exception
    用途:校验一个value是否符合指定类的默认校验组下的某一个属性值。
  6. void validateValue(Class beanType, String propertyName, Object value, Class<?>… groups) throws Exception
    用途:校验一个value是否符合指定类的指定校验组下的某一个属性值。

2.1 定义验证

package com.snt.dms.validator;

import com.snt.dms.validator.impl.PersonNoExistsValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Constraint(validatedBy = PersonNoExistsValidator.class)
public @interface PersonNoExists {

    //提示内容
    String message() default "身份证号已存在";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

2.2 实现验证

package com.snt.dms.validator.impl;

import com.snt.dms.service.PersonService;
import com.snt.dms.validator.PersonNoExists;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PersonNoExistsValidator implements ConstraintValidator<PersonNoExists, String> {

    @Autowired
    PersonService personService;

    @Override
    public void initialize(PersonNoExists constraintAnnotation) {

    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (null == personService.getPersonIdByPersonNo(s)) {
            return true;
        }
        return false;
    }
}

2.3 使用验证

package com.snt.dms.web.vo;

import com.snt.dms.validator.PersonNoExists;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;

public class PersonVO {
    private Integer id;

    @NotBlank
    private String name;

    @NotBlank
    @PersonNoExists
    private String no;

    @Range(min = 1, max = 2, message = "请选择性别")
    private Byte gender;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值