1. 将原先的两个校验器这到一起。

2. 重构、优化代码。
0.4.x
ZhouXY108 2023-01-04 17:51:33 +08:00
parent 864ecf5188
commit 76a9e7dc4e
14 changed files with 741 additions and 465 deletions

View File

@ -1,86 +1,80 @@
package xyz.zhouxy.plusone.validator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
*
*
* <p>
* 使
* </p>
*
* <pre>
* BaseValidator&lt;Integer&gt; validator = new BaseValidator&lt;&gt;() {
* {
* withRule(value -> Objects.nonNull(value), "value 不能为空");
* withRule(value -> (value >= 0 && value <= 500), "value 应在 [0, 500] 内");
* }
* };
* </pre>
*
* <p>
* 使
* </p>
*
* <p>
* {@link #validate}
* {@link ValidateUtil#validate(Object, Validator)}
* </p>
*
* <pre>
* ValidateUtil.validate(255, validator);
* </pre>
*
* <pre>
* validator.validate(666);
* </pre>
* </p>
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
* @see IValidateRequired
* @see ValidateUtil
* @see Validator
*/
public abstract class BaseValidator<T> {
public class BaseValidator<T> {
private final List<Consumer<T>> rules = new ArrayList<>();
private final List<PropertyValidator<T, ?, ?>> propertyValidators = new ArrayList<>();
private final List<RuleInfo<T, ?>> rules = new ArrayList<>();
protected BaseValidator() {
protected void withRule(final Predicate<T> rule, final String errorMessage) {
withRule(rule, value -> new InvalidInputException(errorMessage));
}
protected final void withRule(Predicate<T> rule, String errorMessage) {
withRule(rule, () -> new InvalidInputException(errorMessage));
protected <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionBuilder) {
withRule(rule, value -> exceptionBuilder.get());
}
protected final <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionCreator) {
withRule(rule, value -> exceptionCreator.get());
protected <E extends RuntimeException> void withRule(Predicate<T> condition,
Function<T, E> exceptionBuilder) {
withRule(value -> {
if (!condition.test(value)) {
throw exceptionBuilder.apply(value);
}
});
}
protected final <E extends RuntimeException> void withRule(Predicate<T> rule, Function<T, E> exceptionCreator) {
this.rules.add(new RuleInfo<>(rule, exceptionCreator));
protected void withRule(Consumer<T> rule) {
this.rules.add(rule);
}
protected final <R> ObjectValidator<T, R> ruleFor(Function<T, R> getter) {
ObjectValidator<T, R> validValueHolder = new ObjectValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final IntValidator<T> ruleForInt(Function<T, Integer> getter) {
IntValidator<T> validValueHolder = new IntValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final DoubleValidator<T> ruleForDouble(Function<T, Double> getter) {
DoubleValidator<T> validValueHolder = new DoubleValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final BoolValidator<T> ruleForBool(Function<T, Boolean> getter) {
BoolValidator<T> validValueHolder = new BoolValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final StringValidator<T> ruleForString(Function<T, String> getter) {
StringValidator<T> validValueHolder = new StringValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final <E> CollectionValidator<T, E> ruleForCollection(Function<T, Collection<E>> getter) {
CollectionValidator<T, E> validValueHolder = new CollectionValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
public void validate(T obj) {
this.rules.forEach(ruleInfo -> ruleInfo.validate(obj));
}
protected static class RuleInfo<T, E extends RuntimeException> {
private final Predicate<T> rule;
private final Function<T, E> exceptionCreator;
private RuleInfo(Predicate<T> rule, Function<T, E> exceptionCreator) {
this.rule = rule;
this.exceptionCreator = exceptionCreator;
for (Consumer<T> rule : this.rules) {
rule.accept(obj);
}
private void validate(T obj) {
if (!rule.test(obj)) {
throw exceptionCreator.apply(obj);
}
for (PropertyValidator<T, ?, ?> valueValidator : this.propertyValidators) {
valueValidator.validate(obj);
}
}
}

View File

@ -0,0 +1,56 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
import java.util.function.Supplier;
class BoolValidator<DTO> extends PropertyValidator<DTO, Boolean, BoolValidator<DTO>> {
BoolValidator(Function<DTO, Boolean> getter) {
super(getter);
}
// ====== isTrue ======
public BoolValidator<DTO> isTrue() {
return isTrue("The value must be true.");
}
public BoolValidator<DTO> isTrue(String errMsg) {
return isTrue(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> BoolValidator<DTO> isTrue(Supplier<E> exceptionCreator) {
return isTrue(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> BoolValidator<DTO> isTrue(
Function<Boolean, E> exceptionCreator) {
withRule(Boolean.TRUE::equals, exceptionCreator);
return this;
}
// ====== isFalse ======
public BoolValidator<DTO> isFalse() {
return isFalse("The value must be false.");
}
public BoolValidator<DTO> isFalse(String errMsg) {
return isFalse(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> BoolValidator<DTO> isFalse(Supplier<E> exceptionCreator) {
return isFalse(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> BoolValidator<DTO> isFalse(
Function<Boolean, E> exceptionCreator) {
withRule(Boolean.FALSE::equals, exceptionCreator);
return this;
}
@Override
protected BoolValidator<DTO> returnThis() {
return this;
}
}

View File

@ -0,0 +1,63 @@
package xyz.zhouxy.plusone.validator;
import java.util.Collection;
import java.util.function.Function;
import java.util.function.Supplier;
class CollectionValidator<DTO, T> extends PropertyValidator<DTO, Collection<T>, CollectionValidator<DTO, T>> {
CollectionValidator(Function<DTO, Collection<T>> getter) {
super(getter);
}
// ================================
// ====== Collection, String ======
// ================================
// ====== notEmpty =====
public CollectionValidator<DTO, T> notEmpty(String errMsg) {
return notEmpty(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> CollectionValidator<DTO, T> notEmpty(Supplier<E> exceptionCreator) {
return notEmpty(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> CollectionValidator<DTO, T> notEmpty(
Function<Collection<T>, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
return !((Collection<?>) value).isEmpty();
}, exceptionCreator);
return this;
}
// ====== isEmpty =====
public CollectionValidator<DTO, T> isEmpty(String errMsg) {
return isEmpty(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> CollectionValidator<DTO, T> isEmpty(Supplier<E> exceptionCreator) {
return isEmpty(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> CollectionValidator<DTO, T> isEmpty(
Function<Collection<T>, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
return ((Collection<?>) value).isEmpty();
}, exceptionCreator);
return this;
}
@Override
protected CollectionValidator<DTO, T> returnThis() {
return this;
}
}

View File

@ -0,0 +1,35 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
import java.util.function.Supplier;
class DoubleValidator<DTO> extends PropertyValidator<DTO, Double, DoubleValidator<DTO>> {
DoubleValidator(Function<DTO, Double> getter) {
super(getter);
}
public DoubleValidator<DTO> between(double min, double max) {
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
}
public DoubleValidator<DTO> between(double min, double max, String errMsg) {
return between(min, max, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> DoubleValidator<DTO> between(double min, double max,
Supplier<E> exceptionCreator) {
return between(min, max, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> DoubleValidator<DTO> between(double min, double max,
Function<Double, E> exceptionCreator) {
withRule(value -> (value >= min && value < max), exceptionCreator);
return this;
}
@Override
protected DoubleValidator<DTO> returnThis() {
return this;
}
}

View File

@ -0,0 +1,13 @@
package xyz.zhouxy.plusone.validator;
/**
*
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
*
* @see ValidateUtil
* @see BaseValidator
*/
public interface IValidateRequired {
void validate();
}

View File

@ -0,0 +1,35 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
import java.util.function.Supplier;
class IntValidator<DTO> extends PropertyValidator<DTO, Integer, IntValidator<DTO>> {
IntValidator(Function<DTO, Integer> getter) {
super(getter);
}
public IntValidator<DTO> between(int min, int max) {
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
}
public IntValidator<DTO> between(int min, int max, String errMsg) {
return between(min, max, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> IntValidator<DTO> between(int min, int max,
Supplier<E> exceptionCreator) {
return between(min, max, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> IntValidator<DTO> between(int min, int max,
Function<Integer, E> exceptionCreator) {
withRule(value -> (value >= min && value < max), exceptionCreator);
return this;
}
@Override
protected IntValidator<DTO> returnThis() {
return this;
}
}

View File

@ -0,0 +1,15 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
class ObjectValidator<DTO, T> extends PropertyValidator<DTO, T, ObjectValidator<DTO, T>> {
ObjectValidator(Function<DTO, T> getter) {
super(getter);
}
@Override
protected ObjectValidator<DTO, T> returnThis() {
return this;
}
}

View File

@ -0,0 +1,129 @@
package xyz.zhouxy.plusone.validator;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
abstract class PropertyValidator<DTO, PROPERTY, THIS> {
Function<DTO, PROPERTY> getter;
Validator<PROPERTY> validator = new Validator<>();
PropertyValidator(Function<DTO, PROPERTY> getter) {
this.getter = getter;
}
<E extends RuntimeException> void withRule(Predicate<PROPERTY> condition,
Function<PROPERTY, E> exceptionCreator) {
withRule(value -> {
if (!condition.test(value)) {
throw exceptionCreator.apply(value);
}
});
}
private void withRule(Consumer<PROPERTY> rule) {
this.validator.addRule(rule);
}
// ====================
// ====== Object ======
// ====================
// ====== notNull =====
public THIS notNull() {
return notNull("Value could not be null.");
}
public THIS notNull(String errMsg) {
return notNull(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> THIS notNull(Supplier<E> exceptionCreator) {
return notNull(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> THIS notNull(Function<PROPERTY, E> exceptionCreator) {
withRule(Objects::nonNull, exceptionCreator);
return returnThis();
}
// ====== isNull =====
public THIS isNull(String errMsg) {
return isNull(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> THIS isNull(Supplier<E> exceptionCreator) {
return isNull(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> THIS isNull(Function<PROPERTY, E> exceptionCreator) {
withRule(Objects::isNull, exceptionCreator);
return returnThis();
}
// ===== equals =====
public THIS equalsThat(Object that) {
return equalsThat(that, value -> new InvalidInputException(String.format("(%s) 必须与 (%s) 相等", value, that)));
}
public THIS equalsThat(Object that, String errMsg) {
return equalsThat(that, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> THIS equalsThat(
Object that, Supplier<E> exceptionCreator) {
return equalsThat(that, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> THIS equalsThat(
Object that, Function<PROPERTY, E> exceptionCreator) {
withRule(value -> Objects.equals(value, that), exceptionCreator);
return returnThis();
}
// ===== state =====
public THIS state(Predicate<PROPERTY> condition) {
return state(condition, "无效的用户输入");
}
public THIS state(Predicate<PROPERTY> condition, String errMsg) {
return state(condition, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> THIS state(
Predicate<PROPERTY> condition,
Supplier<E> exceptionCreator) {
return state(condition, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> THIS state(
Predicate<PROPERTY> condition,
Function<PROPERTY, E> exceptionCreator) {
withRule(condition, exceptionCreator);
return returnThis();
}
// ========================================================================
void validate(DTO obj) {
PROPERTY value = this.getter.apply(obj);
this.validator.validate(value);
}
static <V> Function<V, InvalidInputException> convertExceptionCreator(String errMsg) {
return value -> new InvalidInputException(errMsg);
}
static <V, E extends RuntimeException> Function<V, E> convertExceptionCreator(
Supplier<E> exceptionSupplier) {
return value -> exceptionSupplier.get();
}
protected abstract THIS returnThis();
}

View File

@ -0,0 +1,179 @@
package xyz.zhouxy.plusone.validator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import cn.hutool.core.util.StrUtil;
import xyz.zhouxy.plusone.constant.RegexConsts;
import xyz.zhouxy.plusone.util.RegexUtil;
class StringValidator<DTO> extends PropertyValidator<DTO, String, StringValidator<DTO>> {
StringValidator(Function<DTO, String> getter) {
super(getter);
}
// ====================
// ====== String ======
// ====================
// ===== matches =====
public StringValidator<DTO> matches(String regex, String errMsg) {
return matches(regex, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matches(
String regex,
Supplier<E> exceptionCreator) {
return matches(regex, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matches(
String regex,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matches(input, regex), exceptionCreator);
return this;
}
// ===== matchesOr =====
public StringValidator<DTO> matchesOr(String[] regexs, String errMsg) {
return matchesOr(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
String[] regexs,
Supplier<E> exceptionCreator) {
return matchesOr(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
String[] regexs,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesOr(input, regexs), exceptionCreator);
return this;
}
public StringValidator<DTO> matchesOr(List<String> regexs, String errMsg) {
return matchesOr(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
List<String> regexs,
Supplier<E> exceptionCreator) {
return matchesOr(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
List<String> regexs,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesOr(input, regexs.toArray(new String[regexs.size()])), exceptionCreator);
return this;
}
// ===== matchesAnd =====
public StringValidator<DTO> matchesAnd(String[] regexs, String errMsg) {
return matchesAnd(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matchesAnd(
String[] regexs,
Supplier<E> exceptionCreator) {
return matchesAnd(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matchesAnd(
String[] regexs,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesAnd(input, regexs), exceptionCreator);
return this;
}
// ===== notBlank =====
public StringValidator<DTO> notBlank() {
return notBlank("This String argument must have text; it must not be null, empty, or blank");
}
public StringValidator<DTO> notBlank(String errMsg) {
return notBlank(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> notBlank(Supplier<E> exceptionCreator) {
return notBlank(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> notBlank(
Function<String, E> exceptionCreator) {
withRule(input -> StrUtil.isNotBlank(input), exceptionCreator);
return this;
}
// ===== email =====
public StringValidator<DTO> email() {
return email("The value is not an email address.");
}
public StringValidator<DTO> email(String errMsg) {
return email(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> email(Supplier<E> exceptionCreator) {
return email(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> email(Function<String, E> exceptionCreator) {
return matches(RegexConsts.EMAIL, exceptionCreator);
}
// ====== notEmpty =====
public StringValidator<DTO> notEmpty(String errMsg) {
return notEmpty(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> notEmpty(Supplier<E> exceptionCreator) {
return notEmpty(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> notEmpty(
Function<String, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
return !(value.isEmpty());
}, exceptionCreator);
return this;
}
// ====== isEmpty =====
public StringValidator<DTO> isEmpty(String errMsg) {
return isEmpty(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> isEmpty(Supplier<E> exceptionCreator) {
return isEmpty(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> isEmpty(
Function<String, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
return value.isEmpty();
}, exceptionCreator);
return this;
}
@Override
protected StringValidator<DTO> returnThis() {
return this;
}
}

View File

@ -17,6 +17,12 @@ public class ValidateUtil {
throw new IllegalStateException("Utility class");
}
public static void validate(Object obj) {
if (obj instanceof IValidateRequired) {
((IValidateRequired) obj).validate();
}
}
public static <T> void validate(T obj, BaseValidator<T> validator) {
validator.validate(obj);
}

View File

@ -1,6 +1,9 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
*
@ -39,4 +42,19 @@ public final class Validator<T> extends BaseValidator<T> {
withRule(rule, errorMessage);
return this;
}
public final <E extends RuntimeException> Validator<T> addRule(Predicate<T> rule, Supplier<E> exceptionCreator) {
withRule(rule, exceptionCreator);
return this;
}
public final <E extends RuntimeException> Validator<T> addRule(Predicate<T> rule, Function<T, E> exceptionCreator) {
withRule(rule, exceptionCreator);
return this;
}
public final Validator<T> addRule(Consumer<T> rule) {
withRule(rule);
return this;
}
}

View File

@ -1,22 +0,0 @@
package xyz.zhouxy.plusone.validator.validator2;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public abstract class BaseValidator2<T> {
private List<ValueValidator<T, ?>> valueValidators = new ArrayList<>();
protected final <R> ValueValidator<T, R> ruleFor(Function<T, R> getter) {
ValueValidator<T, R> validValueHolder = new ValueValidator<>(getter);
valueValidators.add(validValueHolder);
return validValueHolder;
}
public void validate(T obj) {
for (ValueValidator<T, ?> valueValidator : this.valueValidators) {
valueValidator.validateProperty(obj);
}
}
}

View File

@ -1,379 +0,0 @@
package xyz.zhouxy.plusone.validator.validator2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import cn.hutool.core.util.StrUtil;
import xyz.zhouxy.plusone.constant.RegexConsts;
import xyz.zhouxy.plusone.util.RegexUtil;
import xyz.zhouxy.plusone.validator.InvalidInputException;
public class ValueValidator<DTO, PROPERTY> {
Function<DTO, PROPERTY> getter;
List<Consumer<PROPERTY>> rules = new ArrayList<>();
public ValueValidator(Function<DTO, PROPERTY> getter) {
this.getter = getter;
}
private <E extends RuntimeException> void withRule(Predicate<PROPERTY> condition,
Function<PROPERTY, E> exceptionCreator) {
withRule(value -> {
if (!condition.test(value)) {
throw exceptionCreator.apply(value);
}
});
}
private void withRule(Consumer<PROPERTY> rule) {
this.rules.add(rule);
}
// ====================
// ====== Object ======
// ====================
// ====== notNull =====
public ValueValidator<DTO, PROPERTY> notNull() {
return notNull("Value could not be null.");
}
public ValueValidator<DTO, PROPERTY> notNull(String errMsg) {
return notNull(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notNull(Supplier<E> exceptionCreator) {
return notNull(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notNull(Function<PROPERTY, E> exceptionCreator) {
withRule(Objects::nonNull, exceptionCreator);
return this;
}
// ====== isNull =====
public ValueValidator<DTO, PROPERTY> isNull(String errMsg) {
return isNull(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isNull(Supplier<E> exceptionCreator) {
return isNull(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isNull(Function<PROPERTY, E> exceptionCreator) {
withRule(Objects::isNull, exceptionCreator);
return this;
}
// ===== equals =====
public ValueValidator<DTO, PROPERTY> equalsThat(Object that) {
return equalsThat(that, value -> new InvalidInputException(String.format("(%s) 必须与 (%s) 相等", value, that)));
}
public ValueValidator<DTO, PROPERTY> equalsThat(Object that, String errMsg) {
return equalsThat(that, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> equalsThat(
Object that, Supplier<E> exceptionCreator) {
return equalsThat(that, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> equalsThat(
Object that, Function<PROPERTY, E> exceptionCreator) {
withRule(value -> Objects.equals(value, that), exceptionCreator);
return this;
}
// ===== state =====
public ValueValidator<DTO, PROPERTY> state(Predicate<PROPERTY> condition) {
return state(condition, "无效的用户输入");
}
public ValueValidator<DTO, PROPERTY> state(Predicate<PROPERTY> condition, String errMsg) {
return state(condition, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> state(
Predicate<PROPERTY> condition,
Supplier<E> exceptionCreator) {
return state(condition, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> state(
Predicate<PROPERTY> condition,
Function<PROPERTY, E> exceptionCreator) {
withRule(condition, exceptionCreator);
return this;
}
// =================
// ====== int ======
// =================
public ValueValidator<DTO, PROPERTY> between(int min, int max) {
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
}
public ValueValidator<DTO, PROPERTY> between(int min, int max, String errMsg) {
return between(min, max, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(int min, int max,
Supplier<E> exceptionCreator) {
return between(min, max, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(int min, int max,
Function<PROPERTY, E> exceptionCreator) {
withRule(value -> ((int) value >= min && (int) value < max), exceptionCreator);
return this;
}
// ====================
// ====== double ======
// ====================
public ValueValidator<DTO, PROPERTY> between(double min, double max) {
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
}
public ValueValidator<DTO, PROPERTY> between(double min, double max, String errMsg) {
return between(min, max, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(double min, double max,
Supplier<E> exceptionCreator) {
return between(min, max, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(double min, double max,
Function<PROPERTY, E> exceptionCreator) {
withRule(value -> ((double) value >= min && (double) value < max), exceptionCreator);
return this;
}
// ================================
// ====== Collection, String ======
// ================================
// ====== notEmpty =====
public ValueValidator<DTO, PROPERTY> notEmpty(String errMsg) {
return notEmpty(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notEmpty(Supplier<E> exceptionCreator) {
return notEmpty(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notEmpty(Function<PROPERTY, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
if (value instanceof Collection) {
return !((Collection<?>) value).isEmpty();
}
if (value instanceof String) {
return !((String) value).isEmpty();
}
return false;
}, exceptionCreator);
return this;
}
// ====== isEmpty =====
public ValueValidator<DTO, PROPERTY> isEmpty(String errMsg) {
return isEmpty(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isEmpty(Supplier<E> exceptionCreator) {
return isEmpty(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isEmpty(Function<PROPERTY, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
if (value instanceof Collection) {
return ((Collection<?>) value).isEmpty();
}
if (value instanceof String) {
return ((String) value).isEmpty();
}
return false;
}, exceptionCreator);
return this;
}
// =====================
// ====== boolean ======
// =====================
// ====== isTrue ======
public ValueValidator<DTO, PROPERTY> isTrue() {
return isTrue("The value must be true.");
}
public ValueValidator<DTO, PROPERTY> isTrue(String errMsg) {
return isTrue(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isTrue(Supplier<E> exceptionCreator) {
return isTrue(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isTrue(Function<PROPERTY, E> exceptionCreator) {
withRule(Boolean.TRUE::equals, exceptionCreator);
return this;
}
// ====== isFalse ======
public ValueValidator<DTO, PROPERTY> isFalse() {
return isFalse("The value must be false.");
}
public ValueValidator<DTO, PROPERTY> isFalse(String errMsg) {
return isFalse(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isFalse(Supplier<E> exceptionCreator) {
return isFalse(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isFalse(Function<PROPERTY, E> exceptionCreator) {
withRule(Boolean.FALSE::equals, exceptionCreator);
return this;
}
// ====================
// ====== String ======
// ====================
// ===== matches =====
public ValueValidator<DTO, PROPERTY> matches(String regex, String errMsg) {
return matches(regex, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matches(
String regex,
Supplier<E> exceptionCreator) {
return matches(regex, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matches(
String regex,
Function<PROPERTY, E> exceptionCreator) {
withRule(input -> RegexUtil.matches((String) input, regex), exceptionCreator);
return this;
}
// ===== matchesOr =====
public ValueValidator<DTO, PROPERTY> matchesOr(String[] regexs, String errMsg) {
return matchesOr(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesOr(
String[] regexs,
Supplier<E> exceptionCreator) {
return matchesOr(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesOr(
String[] regexs,
Function<PROPERTY, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesOr((String) input, regexs), exceptionCreator);
return this;
}
// ===== matchesAnd =====
public ValueValidator<DTO, PROPERTY> matchesAnd(String[] regexs, String errMsg) {
return matchesAnd(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesAnd(
String[] regexs,
Supplier<E> exceptionCreator) {
return matchesAnd(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesAnd(
String[] regexs,
Function<PROPERTY, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesAnd((String) input, regexs), exceptionCreator);
return this;
}
// ===== notBlank =====
public ValueValidator<DTO, PROPERTY> notBlank() {
return notBlank("This String argument must have text; it must not be null, empty, or blank");
}
public ValueValidator<DTO, PROPERTY> notBlank(String errMsg) {
return notBlank(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notBlank(Supplier<E> exceptionCreator) {
return notBlank(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notBlank(Function<PROPERTY, E> exceptionCreator) {
withRule(input -> StrUtil.isNotBlank((String) input), exceptionCreator);
return this;
}
// ===== email =====
public ValueValidator<DTO, PROPERTY> email() {
return email("The value is not an email address.");
}
public ValueValidator<DTO, PROPERTY> email(String errMsg) {
return email(convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> email(Supplier<E> exceptionCreator) {
return email(convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> email(Function<PROPERTY, E> exceptionCreator) {
return matches(RegexConsts.EMAIL, exceptionCreator);
}
// ========================================================================
void validateProperty(DTO obj) {
PROPERTY value = this.getter.apply(obj);
for (Consumer<PROPERTY> rule : this.rules) {
rule.accept(value);
}
}
private static <V> Function<V, InvalidInputException> convertExceptionCreator(String errMsg) {
return convertExceptionCreator(errMsg);
}
private static <V, E extends RuntimeException> Function<V, E> convertExceptionCreator(
Supplier<E> exceptionSupplier) {
return value -> exceptionSupplier.get();
}
}

View File

@ -0,0 +1,134 @@
package xyz.zhouxy.plusone.validator;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.junit.Test;
import xyz.zhouxy.plusone.constant.RegexConsts;
public class BaseValidatorTest {
@Test
public void testRuleFor() {
RegisterCommand registerCommand = new RegisterCommand("me", "luquanlion@outlook.com", "22336", "A1b2C3d4",
"A1b2C3d4",
Arrays.asList(new String[] { "admin", "editor" }));
registerCommand.validate();
System.out.println(registerCommand);
}
}
class RegisterCommandValidator extends BaseValidator<RegisterCommand> {
static final RegisterCommandValidator INSTANCE = new RegisterCommandValidator();
private RegisterCommandValidator() {
ruleForString(RegisterCommand::getUsername)
.notNull("用户名不能为空")
.matches(RegexConsts.USERNAME,
username -> new IllegalArgumentException(String.format("用户名\"%s\"不符合规范", username)));
ruleForString(RegisterCommand::getAccount)
.notNull("请输入邮箱地址或手机号")
.matchesOr(new String[] { RegexConsts.EMAIL, RegexConsts.MOBILE_PHONE }, "请输入邮箱地址或手机号");
ruleForString(RegisterCommand::getCode)
.notNull("验证码不能为空")
.matches(RegexConsts.CAPTCHA, "验证码不符合规范");
ruleForString(RegisterCommand::getPassword)
.notEmpty("密码不能为空")
.matches(RegexConsts.PASSWORD, "密码不符合规范");
ruleForCollection(RegisterCommand::getRoles)
.notEmpty(() -> new RuntimeException("角色列表不能为空"));
withRule(registerCommand -> Objects.equals(registerCommand.getPassword(), registerCommand.getPassword2()),
"两次输入的密码不一致");
}
}
/**
* RegisterCommand
*/
class RegisterCommand implements IValidateRequired {
private String username;
private String account;
private String code;
private String password;
private String password2;
private List<String> roles;
@Override
public void validate() {
RegisterCommandValidator.INSTANCE.validate(this);
}
public RegisterCommand() {
}
public RegisterCommand(String username, String account, String code, String password, String password2,
List<String> roles) {
this.username = username;
this.account = account;
this.code = code;
this.password = password;
this.password2 = password2;
this.roles = roles;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("RegisterCommand [username=").append(username).append(", account=").append(account)
.append(", code=").append(code).append(", password=").append(password).append(", password2=")
.append(password2).append(", roles=").append(roles).append("]");
return builder.toString();
}
}