{"id":25015265,"url":"https://github.com/ditschedev/validator","last_synced_at":"2025-04-12T23:13:57.640Z","repository":{"id":40746808,"uuid":"259993389","full_name":"ditschedev/validator","owner":"ditschedev","description":"A simple yet powerfull request validator for Spring Boot incoming DTOs.","archived":false,"fork":false,"pushed_at":"2025-04-12T07:55:01.000Z","size":131,"stargazers_count":5,"open_issues_count":19,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-12T23:13:50.524Z","etag":null,"topics":["builders","dto","rest-api","spring-boot","validation","validator"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ditschedev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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,"zenodo":null}},"created_at":"2020-04-29T17:22:42.000Z","updated_at":"2024-11-14T06:49:45.000Z","dependencies_parsed_at":"2022-08-19T20:20:38.018Z","dependency_job_id":"445d3257-de27-4636-b062-abdded4dbbfa","html_url":"https://github.com/ditschedev/validator","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ditschedev%2Fvalidator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ditschedev%2Fvalidator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ditschedev%2Fvalidator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ditschedev%2Fvalidator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ditschedev","download_url":"https://codeload.github.com/ditschedev/validator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248643006,"owners_count":21138355,"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":["builders","dto","rest-api","spring-boot","validation","validator"],"created_at":"2025-02-05T08:18:35.883Z","updated_at":"2025-04-12T23:13:57.606Z","avatar_url":"https://github.com/ditschedev.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Java Validator\nA rule based validator developed for easy use with the Spring Boot framework.\n\n- *Extendable* ✨: You can always add custom rules\n- *Error format* ✅: You can directly return the result of the failed validation\n- *Well documented* 📑: Always know what you are doing\n\n## Table of contents\n- [Adding dependency](#adding-dependency)\n- [Usage](#usage)\n- [Internationalization](#internationalization)\n- [Builders and Methods](#builders-and-methods)\n    - [`string` rules](#string-rules)\n    - [`number` rules](#number-rules)\n    - [`object` rules](#object-rules)\n    - [`array` rules](#array-rules)\n    - [`temporal` rules](#temporal-rules)\n- [Use with Spring Boot](#use-with-spring-boot)\n- [Custom rules](#custom-rules)\n\n\n---\n\n\n## Adding dependency\nTo use the validator add the following dependency to your `pom.xml`.\n```xml\n\u003cdependency\u003e\n    \u003cgroupId\u003edev.ditsche\u003c/groupId\u003e\n    \u003cartifactId\u003evalidator\u003c/artifactId\u003e\n    \u003cversion\u003e2.3.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n\n---\n\n\n## Usage\n\nEasiest way to use the validator in a Spring Boot project is to setup a `ValidatorConfig` class. There you can\ndefine a bean for each validator you need. Or you can create a validator in the controller method, do it, as you like.\n\nA validator ist built using static helper methods. Here is a working example:\n\n```java\nValidator validator = Validator.fromRules(\n    string(\"name\").required().trim().alphanum().max(50),\n    string(\"gender\").optional().defaultValue(\"m\").max(1),\n    number(\"age\").required().min(18),\n    object(\"tickets\").fields(\n        string(\"event\").required().trim(),\n        temporal(\"date\").required().future()\n    )\n);\n```\n\nThis snippet validates an incoming DTO for the given fields and the nested object `tickets`.\n\nTo validate an object, just call the validate method of the validator. Pass in the object and the optional `abortEarly`\nparameter. This is a boolean indicating, if the `ValidationException` should be thrown after the first validation error\nor at the end if there are any.\n\nMake sure, that if you use altering rules like `defaul()` or `trim()` you reassign the input object with the result of\nthe validate method. That way you get the validated and updated input DTO for further operations.\n\n```java\ndto = validator.validate(dto);\n```\n\n\n---\n\n\n## Internationalization\nUnfortunately it is not possible to change the outputted language to something different than english.\n\nIf you need to provide other languages as well, you can make use of the error type. When\nyou return the result of the `getErrors()` method of the ErrorBag that you got from the thrown\n`ValidationException` you have the error type available and can show messages based on this\nunique key. \n\n\n---\n\n\n## Builders and Methods\nAs said, to generate a validator you should make use of the static helper methods.\nThe following types are supported at the moment:\n- string\n- number (int, long, float, ...)\n- object\n- array\n\nIn the following sections you learn which methods and rules are available by default and how\nto use them. Each `Builder` has a `build()` method which returns a `Validateable`, if you need\nto have one of those.\n\n### `string` rules\n\n#### Usage\nThe following snippet returns an instance of the `StringRuleBuilder` class.\n```java\nstring(field)\n```\n\n#### Available rules\n\n- ##### `required()`\n    Marks the field as *required* meaning it cannot be null or empty.\n    \n- ##### `optional()`\n    Marks the field as *optional*. All rules behind this rule can fail.\n\n- ##### `trim()`\n    *Trims the input and alters* the value to the trimmed string.\n\n- ##### `length(int)`\n    Checks if the provided string has the *exact same length* as the provided parameter `length`.\n    \n- ##### `between(int, int)`\n    Checks if the *length of the string is between* the first and second parameter integers.\n    \n- ##### `min(int)`\n    Checks if the length of the string is *greater or equal* to the given parameter.\n\n- ##### `max(int)`\n    Checks if the length of the string is *smaller or equal* to the given parameter.\n\n- ##### `email()`\n    Checks if the fields value is a *valid email address*.\n\n- ##### `url()`\n    Checks if the fields value is a *valid url*.\n\n- ##### `pattern(String)`\n    Checks if the fields value *matches the given Regex* pattern. The \n    `pattern` parameter should be the `String` representation of a Regex.\n\n- ##### `alphanum()`\n    Checks if the fields value is *alphanumeric*.\n\n- ##### `ip()`\n    Checks if the fields value is a *valid ipv4 address*.\n\n- ##### `creditCard()`\n    Checks if the fields value is a *valid credit card number*.\n\n- ##### `defaultValue(String)`\n    *Sets the fields value to the given string*, if the fields value is null or empty.\n    Rejects if the given parameter is not assignable to the fields value.\n    \n- ##### `custom(Rule)`\n    Registers a custom defined rule.\n\n---    \n\n### `number` rules\n\n#### Usage\nThe following snippet returns an instance of the `NumberRuleBuilder` class.\n```java\nnumber(field)\n```\n\n#### Available rules\n\n- ##### `required()`\n    Marks the field as *required* meaning it cannot be null.\n    \n- ##### `optional()`\n    Marks the field as *optional*. All rules behind this rule can fail.\n\n- ##### `length(int)`\n    Checks if the *fields value is the same* as the provided parameter `length`.\n    \n- ##### `size(int, int)`\n    Checks if the *value is between* the first and second parameter integers.\n    \n- ##### `min(int)`\n    Checks if the fields value is *greater or equal* to the given parameter.\n\n- ##### `max(int)`\n    Checks if the fields value of the string is *smaller or equal* to the given parameter.\n\n- ##### `defaultValue(int)`\n    *Sets the fields value to the given number*, if the fields value is null or 0.\n    Rejects if the given parameter is not assignable to the fields value.\n\n- ##### `custom(Rule)`\n    Registers a custom defined rule.\n\n---\n\n### `object` rules\n\n#### Usage\nThe following snippet returns an instance of the `ObjectRuleBuilder` class.\n```java\nobject(field)\n```\n\n#### Available rules\n\n- ##### `optional()`\n    Marks the field as *optional*. All rules behind this rule can fail.\n    \n- ##### `child(Builder)`\n    Adds a check for *one child property* using a `Builder`.\n\n- ##### `child(Validatable)`\n    Adds a check for *one child property* using a `Validatable`.\n\n- ##### `fields(Builder[])`\n    Adds a check for *one or more child properties* using the given `Builder`.\n\n---\n\n### `array` rules\n\n#### Usage\nThe following snippet returns an instance of the `ArrayRuleBuilder` class.\n```java\narray(field)\n```\n\n#### Available rules\n\n- ##### `required()`\n    Marks the field as *required* meaning it cannot be null or empty.\n    \n- ##### `optional()`\n    Marks the field as *optional*. All rules behind this rule can fail.\n\n- ##### `length(int)`\n    Checks if the *length of the array is the same* as the provided parameter `length`.\n    \n- ##### `size(int, int)`\n    Checks if the *length of the array is between* the first and second parameter integers.\n    \n- ##### `min(int)`\n    Checks if the length of the array is *greater or equal* to the given parameter.\n\n- ##### `max(int)`\n    Checks if the length of the array is *smaller or equal* to the given parameter.\n\n- ##### `objects(Builder[])`\n    *Used for object arrays only!* Gets an array of `Builder` instances, which are validated for every object in the array.\n    \n- ##### `custom(Rule)`\n    Registers a custom defined rule.\n    \n#### Additional methods\n\nArrays are handled differently as they can have elements or objects as children. To handle\nan array of elements you have to use the `elements` method which returns an `ArrayElementRuleBuilder`.\n\n- ##### `elements()`\n    Returns an `ArrayElementRuleBuilder` which has access to nearly every rule from above as\n    the type of the arrays elements is unknown.\n\n\n---\n\n### `temporal` rules\n\n#### Usage\nThe following snippet returns an instance of the `TemporalRuleBuilder` class.\n```java\ntemporal(field)\n```\n\n#### Available rules\n\n- ##### `required()`\n  Marks the field as *required* meaning it cannot be null or empty.\n\n- ##### `optional()`\n  Marks the field as *optional*. All rules behind this rule can fail.\n\n- ##### `past()`\n  Checks if the *value* is before the current timestamp.\n\n- ##### `future()`\n  Checks if the *value* is after the current timestamp.\n\n- ##### `before(temporal)`\n  Takes a temporal object, for example `LocalDateTime`, `LocalDate` or `Date` and compares this to the value. Returns `true`, if the objects value is smaller than the given parameter.\n\n- ##### `after(temporal)`\n  Takes a temporal object, for example `LocalDateTime`, `LocalDate` or `Date` and compares this to the value. Returns `true`, if the objects value is greater than the given parameter.\n\n- ##### `custom(Rule)`\n  Registers a custom defined rule.\n\n---\n\n\n## Use with Spring Boot\nTo make use of the functionalities of Spring Boot and the structure of the errors returned by \nthe `ErrorBag` instance of the thrown `ValidationException` you'd need to define a custom exception\nhandler. Spring Boot makes it easy to create one. \n\nThe following advice generates a well-structured json response that the frontend can use\nto display the errors in the UI. It returns with the `422 Unprocessable Entity` status code\nof http which indicates a validation problem.\n\n```java\n@ControllerAdvice\npublic class ValidationAdvice {\n\n    @ExceptionHandler(ValidationException.class)\n    @ResponseBody\n    public ResponseEntity\u003c?\u003e handleValidationErrors(ValidationException ex) {\n        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(\n                ex.getErrors()\n        );\n    }\n    \n}\n``` \n\nThe resulting json would look like this:\n\n```json\n[\n  {\n    \"field\": \"email\",\n    \"errors\": [\n      {\n        \"message\": \"The field \\\"email\\\" is required\",\n        \"errorType\": \"validation.error.format.required\"\n      },\n      {\n        \"message\": \"The field \\\"email\\\" needs to be a valid email address\",\n        \"errorType\": \"validation.error.format.email\"\n      } \n    ] \n  },\n  ...\n]\n```\n\n\n---\n\n\n## Custom rules\nYou can easily extend the functionality of the validator by defining custom rules. If you need a specific Regex and don't\nwant to use the `PatternRule` over and over again you can create your own rule.\n\nTo do this, implement the `Rule` interface and add an instance of your rule to the validator like shown below:\n\n```java\npublic class MyRule implements Rule {\n    @Override\n    public RuleResult test(Object value) {\n        \n        // Your validation logic\n\n\n        // You have the following methods to generate a result:\n        // RuleResult.reject()              -\u003e Rejects the rule and marks it as not passed.\n        // RuleResult.resolve()             -\u003e Resolve the rule and mark it passed.\n        // RuleResult.resolve(Object)       -\u003e Resolve the rule and update the value of the field.\n        // RuleResult.passes(boolean)       -\u003e Resolves or rejects based on the given boolean or expression.\n        return RuleResult.resolve();\n    }\n\n    @Override\n    public String message(String field) {\n        // The error message\n        return String.format(\"The field \\\"%s\\\" is a custom error\", field);\n    }\n\n    @Override\n    public String getType() {\n        // The error type, to make internationalization possible\n        return RULE_TYPE_PREFIX + \"my.rule\";\n    }\n}\n```\n\nAnd use that rule in a validator:\n\n```java\nValidator.fromRules(\n    ...,\n    string(\"myfield\").custom(new MyRule())\n);\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fditschedev%2Fvalidator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fditschedev%2Fvalidator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fditschedev%2Fvalidator/lists"}