{"id":18253705,"url":"https://github.com/fashionbrot/validation","last_synced_at":"2025-06-19T08:34:56.827Z","repository":{"id":177351432,"uuid":"659801566","full_name":"fashionbrot/validation","owner":"fashionbrot","description":"java、spring、springmvc、springboot、springcloud 参数验证框架","archived":false,"fork":false,"pushed_at":"2025-03-24T03:47:51.000Z","size":964,"stargazers_count":2,"open_issues_count":4,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-04T17:36:53.799Z","etag":null,"topics":["spring-boot-starter-validation","valid","validate","validation","validation-spring","validator"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fashionbrot.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-06-28T15:32:36.000Z","updated_at":"2025-03-21T08:46:59.000Z","dependencies_parsed_at":null,"dependency_job_id":"e826b7dd-201c-4127-8384-af4535133a8d","html_url":"https://github.com/fashionbrot/validation","commit_stats":null,"previous_names":["fashionbrot/validation"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/fashionbrot/validation","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fashionbrot%2Fvalidation","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fashionbrot%2Fvalidation/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fashionbrot%2Fvalidation/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fashionbrot%2Fvalidation/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fashionbrot","download_url":"https://codeload.github.com/fashionbrot/validation/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fashionbrot%2Fvalidation/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260716229,"owners_count":23051404,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["spring-boot-starter-validation","valid","validate","validation","validation-spring","validator"],"created_at":"2024-11-05T10:08:05.031Z","updated_at":"2025-06-19T08:34:51.813Z","avatar_url":"https://github.com/fashionbrot.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"\n\n# 1、项目介绍\n\n  \u003ca href=\"https://www.apache.org/licenses/LICENSE-2.0\"\u003e\n    \u003cimg alt=\"code style\" src=\"https://img.shields.io/badge/license-Apache%202-4EB1BA.svg?style=flat-square\"\u003e\n  \u003c/a\u003e\n\n### 简单好用的 java、spring、springmvc、springboot、springcloud 参数校验框架\n\n#### validation 基于纯java 开发\n\n#### validation-spring 基于spring框架封装的validation\n\n#### spring-boot-starter-validation 基于springboot封装的validation-spring\n\n##### github:https://github.com/fashionbrot/validation.git\n\n##### gitee :https://gitee.com/fashionbrot/validation.git\n\n# 2、使用环境介绍\n\n#### 使用环境介绍\n\n##### jdk8 =\u003e validation\n\n##### spring4.0 \u003e= validation-spring\n\n##### springboot2.0 \u003e= spring-boot-starter-validation\n\n\n# 3、springmvc 引入\n### 3.1 引入maven 配置 和 gradle配置\n```xml\n        \u003c!-- springmvc 依赖--\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.github.fashionbrot\u003c/groupId\u003e\n    \u003cartifactId\u003evalidation-spring\u003c/artifactId\u003e\n    \u003cversion\u003e4.0.2\u003c/version\u003e\n\u003c/dependency\u003e\n```\n```gradle\nimplementation 'com.github.fashionbrot:validation-spring:4.0.2'\n```\n### 3.2  springmvc 配置方式\n```java\n@Component\n@Configuration\n//localeParamName=\"lang\" 开启国际化\n//springProfilesActive=\"prod\" springboot启动的环境\n//@EnableValidatedConfig 开启validation 功能\n@EnableValidatedConfig(localeParamName=\"lang\",springProfilesActive=\"prod\")\npublic class ValidConfig {\n\n}\n```\n### 3.3 配置全局异常拦截\n```java\npackage com.github.fashionbrot.exception;\nimport com.github.fashionbrot.constraint.Violation;\nimport com.github.fashionbrot.util.ObjectUtil;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.validation.BindException;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.ResponseStatus;\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\n\nimport javax.validation.ConstraintViolation;\nimport javax.validation.ConstraintViolationException;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\n\n@RestControllerAdvice\n@Slf4j\npublic class GlobalExceptionHandler {\n\n    @ExceptionHandler(ValidatedException.class)\n    @ResponseStatus(HttpStatus.OK)\n    public Object ValidatedException(ValidatedException e) {\n        List\u003cViolation\u003e violations = e.getViolations();\n\n        return violations.stream().map(m -\u003e m.getMessage()).collect(Collectors.joining(\",\"));// 慢速失败抛出异常信息\n    }\n}\n\n```\n\n### 3.4 使用\n```java\n@RequestMapping(\"/expression\")\n@RestController\npublic class ExpressionController {\n\n    @GetMapping(\"/test1\")\n    @ResponseBody\n    @Validated(failFast = false) //开启参数验证\n    public String test1(Integer type,\n                        @NotEmpty(expression = \"type!=null and type==1 and springProfilesActive=='prod'\",message = \"验证码不能为空\") String smsCode,\n                        @NotEmpty(expression = \"type!=null and type==2 and springProfilesActive=='default'\",message = \"密码不能为空\") String password){\n        return \"ok\";\n    }\n\n    @GetMapping(\"/test2\")\n    @ResponseBody\n    @Validated(failFast = false)//开启参数验证\n    public String test2( ExpressionEntity expression){\n        return expression.toString();\n    }\n\n    @GetMapping(\"/test3\")\n    @ResponseBody\n    @Validated(failFast = false)//开启参数验证\n    public String test3( Default1Entity entity){\n        return entity.toString();\n    }\n\n    @Data\n    //@ValidatedParam(\"expression\")//没有注解默认读取类名首字母小写,例如expressionEntity.type ; 有改注解则表达式中使用例如: expression.type\n    public class ExpressionEntity {\n\n        private Integer type;\n        //如果expression 条件=true,则进行@NotEmpty的验证\n        @NotEmpty(expression = \"expressionEntity.type!=null and expressionEntity.type==1 and springProfilesActive=='prod'\" ,message = \"验证码不能为空\")\n        private String smsCode;\n        //如果expression 条件=true,则进行@NotEmpty的验证\n        @NotEmpty(expression = \"expressionEntity.type!=null and expressionEntity.type==2 and springProfilesActive=='default'\",message = \"密码不能为空\")\n        private String password;\n\n    }\n\n}\n\n```\n\n\n\n# 4、springboot 接入\n### 4.1 Maven引入,gradle引入\n\n```xml\n    \u003c!-- springboot 依赖--\u003e\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.github.fashionbrot\u003c/groupId\u003e\n    \u003cartifactId\u003espring-boot-starter-validation\u003c/artifactId\u003e\n    \u003cversion\u003e4.0.2\u003c/version\u003e\n\u003c/dependency\u003e\n```\n```bash\n #springboot 依赖\nimplementation 'com.github.fashionbrot:spring-boot-starter-validation:4.0.2'\n```\n\n### 4.2 配置方式\n##### application.properties 中配置国际化默认中文\n```properties\n# 开启国际化 优先header读取lang，其次读取参数lang\nvalidated.locale-param-name=lang\n```\n\n### 4.3配置全局异常拦截\n```java\npackage com.github.fashionbrot.exception;\nimport com.github.fashionbrot.constraint.Violation;\nimport com.github.fashionbrot.util.ObjectUtil;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.validation.BindException;\nimport org.springframework.web.bind.annotation.ExceptionHandler;\nimport org.springframework.web.bind.annotation.ResponseStatus;\nimport org.springframework.web.bind.annotation.RestControllerAdvice;\n\nimport javax.validation.ConstraintViolation;\nimport javax.validation.ConstraintViolationException;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n@RestControllerAdvice\n@Slf4j\npublic class GlobalExceptionHandler {\n\n    @ExceptionHandler(ValidatedException.class)\n    @ResponseStatus(HttpStatus.OK)\n    public Object ValidatedException(ValidatedException e) {\n        List\u003cViolation\u003e violations = e.getViolations();\n        return violations.stream().map(m -\u003e m.getMessage()).collect(Collectors.joining(\",\"));\n    }\n}\n```\n### 4.4 在接口中使用\n\n```java\n/**\n* @author fashionbrot\n  */\n@RestController\n@RequestMapping(\"/vrv\")\npublic class ValidReturnValueController {\n\n\n    @GetMapping(\"test1\")\n    @Validated(failFast = false,validReturnValue = true)// 开启参数验证，failFast = false全部校验后抛出异常，validReturnValue = true 验证返回值\n    public ValidReturnValueEntity test1(Integer type){\n        return ValidReturnValueEntity.builder().type(type).build();\n    }\n\n}\n```\n\n\n\n# 4、注解介绍\n\n#### @Validated 添加到方法上开启\n|方法| 默认值                  | 说明                       |\n|------|----------------------|--------------------------|\n|Class\u003c?\u003e[] groups() default { }| {} | 校验组                      |\n|boolean failFast() default true| true                 | true 快速失败                |\n|boolean validReturnValue() default false| false                | 验证返回值 默认false            |\n\n\n#### @Valid 注解支持功能说明，作用于 参数、属性上使用\n#### 用于参数如： `List\u003cUserReq\u003e` userListReq 、UserReq[] userReqs 、List\u003c基本类型\u003e reqList、基本类型[] reqs\n\n\n#### 参数注解\n| 注解          | 作用类型           | 注解说明           |\n|-------------|----------------|----------------|\n| AssertFalse | boolean、String | 只能为false       |\n| AssertTrue  | boolean String    | 只能为true        |\n| BankCard    | String、CharSequence | 验证银行卡          |\n| CreditCard  | String、CharSequence | 验证信用卡          |\n| IdCard      | String、CharSequence | 验证身份证          |\n| Email       | String、CharSequence | 验证邮箱格式         |\n| Digits      | String、CharSequence | 验证是否是数字        |\n| Default     | BigDecimal、BigInteger、Short、Integer、Long、Float、Double、String、CharSequence | 给属性设置默认值       |\n| Length      | String、CharSequence | 验证字符串长度        |\n| Max         | Long、Integer、Short、Float、Double、BigDecimal、BigInteger | 验证属性值不能大于设定值   |\n| Min         | Long、Integer、Short、Float、Double、BigDecimal、BigInteger | 验证属性值不能小于设定值   |\n | NotBlank   | String、CharSequence | 元素值不为空         |\n| NotEmpty | String、CharSequence、Collection、Map、Array | 验证对象不为空        |\n| NotEqualLength | String、CharSequence、Collection、Map、Array | 验证对象长度必须是设定值   |\n | NotNull     | Object | 验证对象不能为空       |\n|Pattern      | String、CharSequence | 验证正则表达式        |\n | Phone      | String、CharSequence | 验证手机号格式        |\n | Range      | BigDecimal、BigInteger、Short、Integer、Long、Float、Double  | 验证属性值必须在 设定值之间 |\n | Contain    | BigDecimal、BigInteger、Short、Integer、Long、Float、Double、String、CharSequence | 验证属性值包含设定值 |\n | Size       | Collection、Map、Array | 验证集合、数组 size 在设定值值之间 |\n\n\n### 固定注解内的方法\n\n| 方法名                                                   | 示例                                                                                                        | 方法说明                                                                                      |\n|-------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|\n| `Class\u003c?\u003e[] groups() default  {}`                     | `@NotNull(message = \"不能为空\", groups = {InsertGroup.class})`                                                  | 用于分组校验，指定注解适用的校验组，例如 `InsertGroup.class`，以便在特定场景下执行相应的校验逻辑                                |\n| `String message() default \"${validated.Length.message}\";` | `@NotNull(message = \"不能为空\")`                                                                                | 指定在验证失败时显示的错误消息内容                                                                         |\n| `String expression() default \"\"`                      | `@NotEmpty(expression = \"type!=null and type==1 and springProfilesActive=='prod'\", message = \"验证码不能为空\") String smsCode` | 当 `expression` 条件为 `true` 时，执行 `@NotEmpty` 验证，适用于基于表达式的条件校验;表达式语法和mybatis xml if 中表达式语法一样 |\n\n\n# 6、自定义注解介绍\n\n#### (1)实现自定义注解的\"注解\"，需要在自定义注解上添加该注解\n```java\npackage com.github.fashionbrot.constraint;\nimport java.lang.annotation.*;\n@Documented\n@Target({ElementType.ANNOTATION_TYPE})\n@Retention(RetentionPolicy.RUNTIME)\npublic @interface Constraint {\n    /**\n     * 属性 参数 实现接口\n     * @return Class\n     */\n    Class\u003c? extends ConstraintValidator\u003c? extends Annotation, ?\u003e\u003e[] validatedBy() default {};\n}\n```\n#### (2)自定义注解必须实现该类\n```java\npackage com.github.fashionbrot.constraint;\nimport java.lang.annotation.Annotation;\n\n/**\n *  自定义注解实现接口，调用顺序 isValid,modify\n * @param \u003cA\u003e Annotation\n * @param \u003cT\u003e T\n */\npublic  interface ConstraintValidator\u003cA extends Annotation, T\u003e {\n\n    /**\n     * annotation all  返回false 抛出异常\n     * @param annotation annotation\n     * @param value value\n     * @param valueType valueType\n     * @return boolean\n     */\n    boolean isValid(A annotation, T value,Class\u003c?\u003e valueType);\n    /**\n     * 修改 value 值,常用于 加密解密字段、脱敏字段 、动态给定默认值、及各种自定义逻辑\n     * @param annotation annotation\n     * @param value value\n     * @param valueType valueType\n     * @return T\n     */\n    default T modify(A annotation,T value,Class\u003c?\u003e valueType){\n        return value;\n    }\n}\n```\n#### (1)创建注解\n```java\npackage com.github.fashionbrot.annotation;\nimport com.github.fashionbrot.constraint.Constraint;\nimport com.github.fashionbrot.constraint.CustomAnnotationConstraintValidator;\nimport java.lang.annotation.*;\n\n@Documented\n@Target({ElementType.FIELD,  ElementType.PARAMETER})\n@Retention(RetentionPolicy.RUNTIME)\n@Constraint(validatedBy = {CustomAnnotationConstraintValidator.class}) //实现类\npublic @interface CustomAnnotation {\n\n    boolean modify() default true;//自己定义\n    String defaultValue() default \"\";//自己定义\n\n    /**\n     * 固定方法  验证失败返回的错误信息\n     * @return\n     */\n    String message() default \"validated.AssertTrue.message\";\n    /**\n     * 固定方法  验证组\n     * default @see com.github.fashionbrot.groups.DefaultGroup\n     * @return groups\n     */\n    Class\u003c?\u003e[] groups() default  {};\n}\n```\n#### 创建注解实现类\n```java\npackage com.github.fashionbrot.constraint;\n\n\nimport com.alibaba.fastjson2.JSON;\nimport com.github.fashionbrot.TestEntity;\nimport com.github.fashionbrot.annotation.CustomAnnotation;\nimport com.github.fashionbrot.util.ObjectUtil;\n\npublic class CustomAnnotationConstraintValidator implements ConstraintValidator\u003cCustomAnnotation, Object\u003e {\n\n    //TODO 自定义注解可以注入spring 容器 bean\n    @Resource\n    private Environment environment;\n\n\n    @Override\n    public boolean isValid(CustomAnnotation annotation, Object value, Class\u003c?\u003e valueType) {\n        //可根据自己逻辑进行拦截\n        return true;\n    }\n\n    @Override\n    public Object modify(CustomAnnotation annotation, Object value, Class\u003c?\u003e valueType) {\n        if (annotation.modify() \u0026\u0026 value==null){\n            if (ObjectUtil.isNotEmpty(annotation.defaultValue())){\n                TestEntity entity = JSON.parseObject(annotation.defaultValue(), TestEntity.class);\n                return entity;\n            }else{\n                //可以根据需求动态修改\n                //TODO 比如加密解密、数据脱敏、增加默认值 等等\n                if (valueType == TestEntity.class){\n                    TestEntity entity = new TestEntity();\n                    entity.setId(2L);\n                    entity.setName(\"李四\");\n                    return entity;\n                }\n            }\n        }\n        return value;\n    }\n}\n```\n#### (3) 在接口上使用\n```java\n    @Controller\n    public class Controller1{\n\n        @Validated(failFast = false)//TODO 添加该注解开启参数验证\n        public void test(@CustomAnnotation(defaultValue = \"{\\\"id\\\":1,\\\"name\\\":\\\"张三\\\"}\",modify = true) TestEntity test){\n\n        }\n    }\n```\n\n\n# 7使用国际化 【默认支持中文、英文,其他语言自己可添加】\n```properties\n# 开启国际化 优先header读取lang，其次读取参数lang\nvalidated.locale-param-name=lang\n```\n\n##### 如果需要添加新语言，可以在 resources 目录下增加对应的属性文件。例如，添加俄语支持：\n##### valid_ru_RU.properties\n```properties\n#valid_ru_RU.properties\nvalidated.NotEmpty.message= `не должно быть пустым\n```\n#####在我们header 中可以配置参数  lang=ru_RU  并且message等于默认的${validated.NotEmpty.message}\n```shell\nlang=ru_RU  message=${validated.NotEmpty.message}   则会提示：`не должно быть пустым`\nlang=zh_CN  message=${validated.NotEmpty.message}   则会提示：`不能为空`\nlang=en_US  message=${validated.NotEmpty.message}   则会提示：`must not be empty`\n```\n\n\n\n\n\n# 版权 | License\n\n[Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0)\n\n\n\n# 捐赠 | Donate\n\n\u003e [捐赠记录,感谢你们的支持！](https://gitee.com/fashionbrot/validation/wikis/%E6%8D%90%E8%B5%A0%E8%AE%B0%E5%BD%95)\n\u003cp \u003e\n\u003cimg alt=\"Image text\" height=\"450\" width=\"350\"  src=\"./doc/zfb.jpg\" title=\"捐赠给 validation\" /\u003e\n\u003cimg alt=\"Image text\" height=\"450\" width=\"350\" src=\"./doc/wx.jpg\" title=\"捐赠给 validation\" /\u003e\n\u003c/p\u003e\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffashionbrot%2Fvalidation","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffashionbrot%2Fvalidation","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffashionbrot%2Fvalidation/lists"}