自定义字段验证

1.定义@interface

package com.jwt.jwt.inter;

import javax.validation.Constraint;
import javax.validation.Payload;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target( FIELD )
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { NameValidationMethod.class})
public @interface NameValidation {

    String message() default "{javax.validation.name.validation.message.not.null}";

    Class[] groups() default { };

    Class[] payload() default { };
}

  1. 具体验证类
package com.jwt.jwt.inter;

import org.apache.commons.lang3.StringUtils;

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

public class NameValidationMethod implements ConstraintValidator {
    @Override
    public void initialize(NameValidation constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StringUtils.isBlank(value)){
            return false;
        }
        return true;
    }
}

你可能感兴趣的:(tips,java)