表單驗證工具類ValidationUtils

小螞蟻hjk發表於2020-12-18

在這裡插入圖片描述
import com.google.common.collect.Maps;
import com.yunjiacloud.nj.spacex.exception.SpaceXException;
import com.yunjiacloud.nj.spacex.util.JsonUtils;
import com.yunjiacloud.nj.spacex.util.RegexUtils;
import com.yunjiacloud.nj.spacex.util.ValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.MapBindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

import javax.validation.Validation;
import java.math.BigDecimal;
import java.util.Map;

@Slf4j
public abstract class ValidationUtils {

private static final javax.validation.Validator javaxValidator =
Validation.buildDefaultValidatorFactory().getValidator();
private static final SpringValidatorAdapter validator =
new SpringValidatorAdapter(javaxValidator);

public static MapBindingResult errors(String name) {
return new MapBindingResult(Maps.newHashMap(), name);
}

public static boolean validateBean(String field, T value, Errors errors, Class… groups) {
Errors err = errors(errors.getObjectName());
err.setNestedPath(field);
org.springframework.validation.ValidationUtils.invokeValidator(validator, value, err, groups);
if (err.hasErrors()) {
errors.addAllErrors(err);
return false;
}
return true;
}

public static boolean validateEmail(String field, String value, String message, Errors errors) {
if (!ValidatorUtils.checkEmail(value)) {
errors.rejectValue(field, null, message);
return false;
}
return true;
}

public static boolean validateLength(
String field, String value, int min, int max, String message, Errors errors) {
if (value == null) {
return true;
} else {
int length = value.length();
if (length >= min && length <= max) {
return true;
}
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validateURL(String field, String value, String message, Errors errors) {
if (!ValidatorUtils.checkURL(value)) {
errors.rejectValue(field, null, message);
return false;
}
return true;
}

public static boolean validateNull(String field, String value, String message, Errors errors) {
if (null != value) {
errors.rejectValue(field, null, message);
return false;
}
return true;
}

public static boolean validateNotNull(String field, String value, String message, Errors errors) {
if (null == value) {
errors.rejectValue(field, null, message);
return false;
}
return true;
}

public static boolean validateNotNull(String field, Object value, String message, Errors errors) {
if (null == value) {
errors.rejectValue(field, null, message);
return false;
}
return true;
}

public static boolean validateTrue(String field, boolean value, String message, Errors errors) {
if (!value) {
errors.rejectValue(field, null, message);
return false;
}
return true;
}

public static boolean validateFalse(String field, boolean value, String message, Errors errors) {
if (value) {
errors.rejectValue(field, null, message);
return false;
}
return true;
}

public static boolean validateMin(
String field, String value, Number min, String message, Errors errors) {
if (value == null) {
return true;
} else {
try {
if ((new BigDecimal(value)).compareTo(new BigDecimal(min.toString())) != -1) {
return true;
}
} catch (NumberFormatException e) {
}
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validateMin(
String field, Number value, Number min, String message, Errors errors) {
if (value == null) {
return true;
}
return validateMin(field, value.toString(), min, message, errors);
}

public static boolean validateMax(
String field, String value, Number max, String message, Errors errors) {
if (value == null) {
return true;
} else {
try {
if ((new BigDecimal(value)).compareTo(new BigDecimal(max.toString())) != 1) {
return true;
}
} catch (NumberFormatException e) {
}
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validateMax(
String field, Number value, Number max, String message, Errors errors) {
if (value == null) {
return true;
}
return validateMax(field, value.toString(), max, message, errors);
}

public static boolean validateRange(
String field, String value, Number min, Number max, String message, Errors errors) {
if (value == null) {
return true;
} else {
try {
BigDecimal val = new BigDecimal(value);
if (val.compareTo(new BigDecimal(min.toString())) != -1
&& val.compareTo(new BigDecimal(max.toString())) != 1) {
return true;
}
} catch (NumberFormatException e) {
}
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validateRange(
String field, Number value, Number min, Number max, String message, Errors errors) {
if (value == null) {
return true;
}
return validateRange(field, value.toString(), min, max, message, errors);
}

public static boolean validateDigits(String field, String value, String message, Errors errors) {
if (value == null || RegexUtils.matches("\-?[1-9]\d*", value)) {
return true;
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validatePattern(
String field, String value, String regex, String message, Errors errors) {
if (value == null || RegexUtils.matches(regex, value)) {
return true;
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validateMobile(String field, String value, String message, Errors errors) {
if (value == null || ValidatorUtils.checkMobile(value)) {
return true;
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validatePhone(String field, String value, String message, Errors errors) {
if (value == null || ValidatorUtils.checkPhone(value)) {
return true;
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validatePostcode(
String field, String value, String message, Errors errors) {
if (value == null || ValidatorUtils.checkPostcode(value)) {
return true;
}
errors.rejectValue(field, null, message);
return false;
}

public static boolean validateIdCard(String field, String value, String message, Errors errors) {
if (value == null || ValidatorUtils.checkIdCard(value)) {
return true;
}
errors.rejectValue(field, null, message);
return false;
}

public static void checkErrors(Errors errors) {
if (errors.hasErrors()) {
Map<String, String> errorMsg = Maps.newHashMap();
for (ObjectError oe : errors.getAllErrors()) {
if (oe instanceof FieldError) {
FieldError fieldError = (FieldError) oe;
errorMsg.put(oe.getObjectName() + “.” + fieldError.getField(), oe.getDefaultMessage());
} else {
errorMsg.put(oe.getObjectName(), oe.getDefaultMessage());
}
}
log.error(“校驗不通過:{}”, JsonUtils.stringify(errorMsg));
throw new ValidationException(JsonUtils.stringify(errorMsg), “校驗不通過”);
}
}

public static class ValidationException extends SpaceXException {

private String errors;

public ValidationException(String errors, String message) {
  super(null, message);
  this.errors = errors;
}

@Override
protected void initData(String code, Object[] params) {}

@Override
public String getCode() {
  return String.valueOf(getHttpStatusCode());
}

@Override
public String getBusinessMessage() {
  return this.errors;
}

@Override
public int getHttpStatusCode() {
  return 406;
}

}
}

應用
@PostMapping("/pwd/update")
@ApiOperation(“修改密碼”)
public Boolean resetPwd(@Validated JurorResetPwdDto resetPwdDto, Errors errors) {
ValidationUtils.checkErrors(errors);
resetPwdDto.setUserId(SessionUtil.getCurrentUserId());
resetPwdDto.setTenantCode(SessionUtil.getCurrentTenantCode());
return jurorService.updatePassword(resetPwdDto);
}

相關文章