背景
在前后端開發過程中,數據校驗是一項必須且常見的事,從展示層、業務邏輯層到持久層幾乎每層都需要數據校驗。如果在每一層中手工實現驗證邏輯,既耗時又容易出錯。
為了避免重復這些驗證,通常的做法是將驗證邏輯直接捆綁到領域模型中,通過元數據(默認是注解)去描述模型, 生成校驗代碼,從而使校驗從業務邏輯中剝離,提升開發效率,使開發者更專注業務邏輯本身。
在 Spring 中,目前支持兩種不同的驗證方法:Spring Validation 和 JSR-303 Bean Validation,即 @Validated(org . springframework.validation.annotation.Validated)和 @Valid(javax.validation.Valid)。兩者都可以通過定義模型的約束來進行數據校驗,雖然兩者使用類似,在很多場景下也可以相互替換,但實際上卻完全不同,這些差別長久以來對我們日常使用產生了較大疑惑,本文主要梳理其中的差別、介紹 Validation 的使用及其實現原理,幫助大家在實踐過程中更好使用 Validation 功能。
二
Bean Validation簡介
什么是JSR?
JSR-303定義的是什么標準?
常用的校驗注解補充:
@NotBlank 檢查約束字符串是不是 Null 還有被 Trim 的長度是否大于,只對字符串,且會去掉前后空格。
@NotEmpty 檢查約束元素是否為 Null 或者是 Empty。
@Length 被檢查的字符串長度是否在指定的范圍內。
@Email 驗證是否是郵件地址,如果為 Null,不進行驗證,算通過驗證。
@Range 數值返回校驗。
@IdentityCardNumber 校驗身份證信息。
@UniqueElements 集合唯一性校驗。
@URL 驗證是否是一個 URL 地址。
Spring Validation的產生背景
Spring 增加 @Validated 是為了支持分組校驗,即同一個對象在不同的場景下使用不同的校驗形式。比如有兩個步驟用于提交用戶資料,后端復用的是同一個對象,第一步驗證姓名,電子郵件等字段,然后在后續步驟中的其他字段中。這時候分組校驗就會發揮作用。
之所以沒有將它添加到 @Valid 注釋中,是因為它是使用 Java 社區過程(JSR-303)標準化的,這需要時間,而 Spring 開發者想讓人們更快地使用這個功能。
Spring 增加 @Validated 還有另一層原因,Bean Validation 的標準做法是在程序中手工調用 Validator 或者 ExecutableValidator 進行校驗,為了實現自動化,通常通過 AOP、代理等方法攔截技術來調用。而 @Validated 注解就是為了配合 Spring 進行 AOP 攔截,從而實現 Bean Validation 的自動化執行。
@Valid 是 JSR 標準 API,@Validated 擴展了 @Valid 支持分組校驗且能作為 SpringBean 的 AOP 注解,在 SpringBean 初始化時實現方法層面的自動校驗。最終還是使用了 JSR API 進行約束校驗。
三
Bean Validation的使用
引入POM
// 正常應該引入hibernate-validator,是JSR的參考實現
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
// Spring在stark中集成了,所以hibernate-validator可以不用引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Bean層面校驗
public class EntryApplicationInfoCmd {
/**
* 用戶ID
*/
@NotNull(message="用戶ID不為空")
private Long userId;
/**
* 證件類型
*/
@NotEmpty(message="證件類型不為空")
private String certType;
}
主要為了限制 Setter 方法的只讀屬性。屬性的 Getter 方法打注釋,而不是 Setter。
public class EntryApplicationInfoCmd {
public EntryApplicationInfoCmd(Long userId, String certType) {
this.userId=userId;
this.certType=certType;
}
/**
* 用戶ID
*/
private Long userId;
/**
* 證件類型
*/
private String certType;
@NotNull
public String getUserId() {
return userId;
}
@NotEmpty
public String getCertType() {
return userId;
}
}
public class EntryApplicationInfoCmd {
...
List<@NotEmpty Long> categoryList;
}
@CategoryBrandNotEmptyRecord 是自定義類層面的約束,也可以約束在構造函數上。
@CategoryBrandNotEmptyRecord
public class EntryApplicationInfoCmd {
/**
* 用戶ID
*/
@NotNull(message="用戶ID不為空")
private Long userId;
List<@NotEmpty Long> categoryList;
}
嵌套對象需要額外使用 @Valid 進行標注(@Validate 不支持,為什么?請看產生的背景)。
public class EntryApplicationInfoCmd {
/**
* 主營品牌
*/
@Valid
@NotNull
private MainBrandImagesCmd mainBrandImage;
}
public class MainBrandImagesCmd {
/**
* 品牌名稱
*/
@NotEmpty
private String brandName;;
}
// 獲取校驗器
ValidatorFactory factory=Validation.buildDefaultValidatorFactory();
Validator validator=factory.getValidator();
// 進行bean層面校驗
Set<ConstraintViolation<User>> violations=validator.validate(EntryApplicationInfoCmd);
// 打印校驗信息
for (ConstraintViolation<User> violation : violations) {
log.error(violation.getMessage());
}
方法層面校驗
public class MerchantMainApplyQueryService {
MainApplyDetailResp detail(@NotNull(message="申請單號不能為空") Long id) {
...
}
}
public class MerchantMainApplyQueryService {
@NotNull
@Size(min=1)
public List<@NotNull MainApplyStandDepositResp> getStanderNewDeposit(Long id) {
//...
}
}
嵌套對象需要額外使用 @Valid 進行標注(@Validate 不支持)。
public class MerchantMainApplyQueryService {
public NewEntryBrandRuleCheckApiResp brandRuleCheck(@Valid @NotNull NewEntryBrandRuleCheckRequest request) {
...
}
}
public class NewEntryBrandRuleCheckRequest {
@NotNull(message="一級類目不能為空")
private Long level1CategoryId;
}
Validation 的設計需要遵循里氏替換原則,無論何時使用類型 T,也可以使用 T 的子類型 S,而不改變程序的行為。即子類不能增加約束也不能減弱約束。
子類方法參數的約束與父類行為不一致(錯誤例子):
// 繼承的方法參數約束不能改變,否則會導致父類子類行為不一致
public interface Vehicle {
void drive(@Max(75) int speedInMph);
}
public class Car implements Vehicle {
@Override
public void drive(@Max(55) int speedInMph) {
//...
}
}
方法的返回值可以增加約束(正確例子):
// 繼承的方法返回值可以增加約束
public interface Vehicle {
@NotNull
List<Person> getPassengers();
}
public class Car implements Vehicle {
@Override
@Size(min=1)
public List<Person> getPassengers() {
//...
return null;
}
}
方法層面校驗使用的是 ExecutableValidator。
// 獲取校驗器
ValidatorFactory factory=Validation.buildDefaultValidatorFactory();
Validator executableValidator=factory.getValidator().forExecutables();
// 進行方法層面校驗
MerchantMainApplyQueryService service=getService();
Method method=MerchantMainApplyQueryService.class.getMethod( "getStanderNewDeposit", int.class );
Object[] parameterValues={ 80 };
Set<ConstraintViolation<Car>> violations=executableValidator.validateParameters(
service,
method,
parameterValues
);
// 打印校驗信息
for (ConstraintViolation<User> violation : violations) {
log.error(violation.getMessage());
}
分組校驗
public class NewEntryMainApplyRequest {
@NotNull(message="一級類目不能為空")
private Long level1CategoryId;
@NotNull(message="申請單ID不能為空", group=UpdateMerchantMainApplyCmd.class)
private Long applyId;
@NotEmpty(message="審批人不能為空", group=AddMerchantMainApplyCmd.class)
private String operator;
}
// 校驗分組UpdateMerchantMainApplyCmd.class
NewEntryMainApplyRequest request1=new NewEntryMainApplyRequest( 29, null, "aaa");
Set<ConstraintViolation<NewEntryMainApplyRequest>> constraintViolations=validator.validate( request1, UpdateMerchantMainApplyCmd.class );
assertEquals("申請單ID不能為空", constraintViolations.iterator().next().getMessage());
// 校驗分組AddMerchantMainApplyCmd.class
NewEntryMainApplyRequest request2=new NewEntryMainApplyRequest( 29, "12345", "");
Set<ConstraintViolation<NewEntryMainApplyRequest>> constraintViolations=validator.validate( request2, AddMerchantMainApplyCmd.class );
assertEquals("審批人不能為空", constraintViolations.iterator().next().getMessage());
自定義校驗
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=MyConstraintValidator.class)
public @interface MyConstraint {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定義校驗器:
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
@Override
public void initialize(MyConstraint constraintAnnotation) {
}
@Override
public isValid isValid(Object value, ConstraintValidatorContext context) {
String name=(String)value;
if("xxxx".equals(name)) {
return true;
}
return false;
}
}
使用自定義約束:
public class Test {
@MyConstraint(message="test")
String name;
}
四
Bean Validation自動執行以及原理
Validation的常見誤解
Spring-mvc 中在 @RequestBody 后面加 @Validated、@Valid 約束即可生效。
@RestController
@RequestMapping("/biz/merchant/enter")
public class MerchantEnterController {
@PostMapping("/application")
// 使用@Validated
public HttpMessageResult addOrUpdateV1(@RequestBody @Validated MerchantEnterApplicationReq req){
...
}
// 使用@Valid
@PostMapping("/application2")
public HttpMessageResult addOrUpdate2(@RequestBody @Valid MerchantEnterApplicationReq req){
...
}
}
然而下面這個約束其實是不生效的,想要生效得在 MerchantEntryServiceImpl 類目加上 @Validated 注解。
// @Validated 不加不生效
@Service
public class MerchantEntryService {
public Boolean applicationAddOrUpdate(@Validated MerchantEnterApplicationReq req) {
...
}
public Boolean applicationAddOrUpdate2(@Valid MerchantEnterApplicationReq req) {
...
}
}
那么究竟為什么會出現這種情況呢,這就需要對 Spring Validation 的注解執行原理有一定的了解。
Controller自動執行約束校驗原理
public class RequestResponseBodyMethodProcessor extends AbstractMessageConverterMethodProcessor {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(RequestBody.class);
}
// 類上或者方法上標注了@ResponseBody注解都行
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return (AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ResponseBody.class) || returnType.hasMethodAnnotation(ResponseBody.class));
}
// 這是處理入參封裝校驗的入口
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
parameter=parameter.nestedIfOptional();
// 獲取請求的參數對象
Object arg=readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
// 獲取參數名稱
String name=Conventions.getVariableNameForParameter(parameter);
// 只有存在binderFactory才會去完成自動的綁定、校驗~
if (binderFactory !=null) {
WebDataBinder binder=binderFactory.createBinder(webRequest, arg, name);
if (arg !=null) {
// 這里完成數據綁定+數據校驗~~~~~(綁定的錯誤和校驗的錯誤都會放進Errors里)
validateIfApplicable(binder, parameter);
// 若有錯誤消息hasErrors(),并且僅跟著的一個參數不是Errors類型,Spring MVC會主動給你拋出MethodArgumentNotValidException異常
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
}
}
// 把錯誤消息放進去 證明已經校驗出錯誤了~~~
// 后續邏輯會判斷MODEL_KEY_PREFIX這個key的~~~~
if (mavContainer !=null) {
mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
}
}
return adaptArgumentIfNecessary(arg, parameter);
}
...
}
約束的校驗邏輯是在 RequestResponseBodyMethodProcessor.validateIfApplicable 實現的,這里同時兼容了 @Validated 和 @Valid,所以該場景下兩者是等價的。
// 校驗,如果合適的話。使用WebDataBinder,失敗信息最終也都是放在它身上~
// 入參:MethodParameter parameter
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
// 拿到標注在此參數上的所有注解們(比如此處有@Valid和@RequestBody兩個注解)
Annotation[] annotations=parameter.getParameterAnnotations();
for (Annotation ann : annotations) {
// 先看看有木有@Validated
Validated validatedAnn=AnnotationUtils.getAnnotation(ann, Validated.class);
// 這個里的判斷是關鍵:可以看到標注了@Validated注解 或者注解名是以Valid打頭的 都會有效哦
//注意:這里可沒說必須是@Valid注解。實際上你自定義注解,名稱只要一Valid開頭都成~~~~~
if (validatedAnn !=null || ann.annotationType().getSimpleName().startsWith("Valid")) {
// 拿到分組group后,調用binder的validate()進行校驗~~~~
// 可以看到:拿到一個合適的注解后,立馬就break了~~~
// 所以若你兩個主機都標注@Validated和@Valid,效果是一樣滴~
Object hints=(validatedAnn !=null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
Object[] validationHints=(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
binder.validate(validationHints);
break;
}
}
binder.validate() 的實現中使用的 org.springframework.validation.Validator 的接口,該接口的實現為 SpringValidatorAdapter。
public void validate(Object... validationHints) {
Object target=getTarget();
Assert.state(target !=null, "No target to validate");
BindingResult bindingResult=getBindingResult();
for (Validator validator : getValidators()) {
// 使用的org.springframework.validation.Validator,調用SpringValidatorAdapter.validate
if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) {
((SmartValidator) validator).validate(target, bindingResult, validationHints);
}
else if (validator !=null) {
validator.validate(target, bindingResult);
}
}
}
在 ValidatorAdapter.validate 實現中,最終調用了 javax.validation.Validator.validate,也就是說最終是調用 JSR 實現,@Validate 只是外層的包裝,在這個包裝中擴展的分組功能。
public class SpringValidatorAdapter {
...
private javax.validation.Validator targetValidator;
@Override
public void validate(Object target, Errors errors) {
if (this.targetValidator !=null) {
processConstraintViolations(
// 最終是調用JSR實現
this.targetValidator.validate(target), errors));
}
}
}
targetValidator.validate 就是 javax.validation.Validator.validate 上述 2.6 Bean 層面手工驗證一致。
Service自動執行約束校驗原理
非Controller的@RequestBody注解,自動執行約束校驗,是通過 MethodValidationPostProcessor 實現的,該類繼承。
BeanPostProcessor, 在 Spring Bean 初始化過程中讀取 @Validated 注解創建 AOP 代理(實現方式與 @Async 基本一致)。該類開頭文檔注解(JSR 生效必須類層面上打上 @Spring Validated 注解)。
/**
* <p>Target classes with such annotated methods need to be annotated with Spring's
* {@link Validated} annotation at the type level, for their methods to be searched for
* inline constraint annotations. Validation groups can be specified through {@code @Validated}
* as well. By default, JSR-303 will validate against its default group only.
*/
public class MethodValidationPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor
implements InitializingBean {
private Class<? extends Annotation> validatedAnnotationType=Validated.class;
@Nullable
private Validator validator;
.....
/**
* 設置Validator
* Set the JSR-303 Validator to delegate to for validating methods.
* <p>Default is the default ValidatorFactory's default Validator.
*/
public void setValidator(Validator validator) {
// Unwrap to the native Validator with forExecutables support
if (validator instanceof LocalValidatorFactoryBean) {
this.validator=((LocalValidatorFactoryBean) validator).getValidator();
}
else if (validator instanceof SpringValidatorAdapter) {
this.validator=validator.unwrap(Validator.class);
}
else {
this.validator=validator;
}
}
/**
* Create AOP advice for method validation purposes, to be applied
* with a pointcut for the specified 'validated' annotation.
* @param validator the JSR-303 Validator to delegate to
* @return the interceptor to use (typically, but not necessarily,
* a {@link MethodValidationInterceptor} or subclass thereof)
* @since 4.2
*/
protected Advice createMethodValidationAdvice(@Nullable Validator validator) {
// 創建了方法調用時的攔截器
return (validator !=null ? new MethodValidationInterceptor(validator) : new MethodValidationInterceptor());
}
}
真正執行方法調用時,會走到 MethodValidationInterceptor.invoke,進行約束校驗。
public class MethodValidationInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// Avoid Validator invocation on FactoryBean.getObjectType/isSingleton
if (isFactoryBeanMetadataMethod(invocation.getMethod())) {
return invocation.proceed();
}
// Standard Bean Validation 1.1 API
ExecutableValidator execVal=this.validator.forExecutables();
...
try {
// 執行約束校驗
result=execVal.validateParameters(
invocation.getThis(), methodToValidate, invocation.getArguments(), groups);
}
catch (IllegalArgumentException ex) {
// Probably a generic type mismatch between interface and impl as reported in SPR-12237 / HV-1011
// Let's try to find the bridged method on the implementation class...
methodToValidate=BridgeMethodResolver.findBridgedMethod(
ClassUtils.getMostSpecificMethod(invocation.getMethod(), invocation.getThis().getClass()));
result=execVal.validateParameters(
invocation.getThis(), methodToValidate, invocation.getArguments(), groups);
}
...
return returnValue;
}
}
execVal.validateParameters 就是 javax.validation.executable.ExecutableValidator.validateParameters 與上述 3.5 方法層面手工驗證一致。
五
總結
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single
作者:洛峰
來源:微信公眾號:得物技術
出處:https://mp.weixin.qq.com/s/Z7bM6vP-lHJzkzeHpN8N0g
日常開發中,我們有時候需要判斷用戶輸入的是數字還是字母。本文將介紹如何用JavaScript實現這一功能。
要判斷輸入值是數字還是字母,我們可以通過JavaScript獲取輸入框的值,然后使用isNaN函數來檢查輸入值是否為數字。
例如,假設我們有如下表單:
<form name="myForm">
年齡: <input type="text" name="age">
<input type="submit" value="提交">
</form>
我們可以通過以下JavaScript代碼來獲取表單,并檢查age字段中是否輸入了數字:
const { myForm }=document.forms;
myForm.addEventListener('submit', (e)=> {
e.preventDefault();
const x=myForm.age.value;
if (isNaN(x)) {
alert("必須輸入數字");
}
});
const { myForm }=document.forms;
通過document.forms獲取表單,并使用解構賦值的方式獲取我們需要的myForm表單。
myForm.addEventListener('submit', (e)=> {
e.preventDefault();
})
使用addEventListener方法監聽表單的submit事件,并在事件觸發時執行回調函數。回調函數中,首先調用e.preventDefault()來阻止表單的默認提交行為。
const x=myForm.age.value;
從表單中獲取age輸入框的值。
if (isNaN(x)) {
alert("必須輸入數字");
}
使用isNaN函數檢查輸入值是否為數字。如果isNaN返回true,說明輸入的不是數字,此時彈出警告框提示用戶“必須輸入數字”。
通過以上步驟,我們可以輕松地用JavaScript判斷輸入值是數字還是字母。isNaN函數在這里起到了關鍵作用,它能夠有效地幫助我們識別非數字輸入。在實際開發中,這種驗證方式能夠提高表單數據的準確性,提升用戶體驗。
希望這篇文章對你有所幫助,趕快試試在你的項目中實現這個功能吧!如果有任何問題或疑惑,歡迎在評論區留言討論。
很多網站注冊的時候,需要我們填寫電話號碼,本文主要介紹了javascript實現判斷電話號碼實例,需要的朋友可以參考下:
效果:
html:
span標簽里面的內容主要是用來寫提示的,比如輸錯了,就會提示您“請輸入正確的手機號” 如果輸的正確,就會提示“OK”;
js代碼:
*請認真填寫需求信息,我們會在24小時內與您取得聯系。