English | 简体ä¸ć–‡
Validator
is an npm package that provides a flexible and extensible validation framework for validating data based on a set of rules. It allows you to define validation rules using various strategies and perform validation on different types of data.
To install the Validator
package, you can use npm or yarn:
npm install js-easy-validator -S
or
yarn add js-easy-validator
- Define validation rules using a set of predefined strategies.
- Extensible architecture allows adding custom validation strategies.
- Supports required field validation, regular expression pattern matching, and custom validation functions.
- Provides a simple and consistent API for adding rules and running validations.
To start using the Validator
, you need to create an instance by providing an array of validation rules. Each rule is defined using the RuleItem
type, which can be one of the following:
RuleItemRequired
: Specifies that a field is required.RuleItemReg
: Specifies a regular expression pattern that the field should match.RuleItemValidator
: Specifies a custom validation function.RuleItemField
: Specifies additional field properties (e.g., message, type).
Example:
import { Validator } from "js-easy-validator";
const rules = [
{ required: true, message: "Field is required" },
{ reg: /^[A-Z]+$/, message: "Field should contain uppercase letters only" },
{
validator: (rule, value) =>
value.length >= 5 ? undefined : "Field should have at least 5 characters",
},
];
const validator = new Validator(rules);
validator.run(""); // Field is required
validator.run("test"); // Field should contain uppercase letters only
validator.run("S"); // Field should have at least 5 characters
validator.run("VALIDATOR"); // Validation passed and returned ""
You can add additional rules to the Validator
instance using the add
method. The rules will be appended to the existing set of rules.
validator.add({ required: true, message: "Another field is required" });
To perform validations on a value, use the run
method of the Validator
instance. It takes the value as an argument and returns an error message if validation fails, or an empty string if the value is valid.
const value = "ABC";
const errorMessage = validator.run(value);
if (errorMessage) {
console.error(errorMessage);
} else {
console.log("Value is valid");
}
The Validator
supports custom validation strategies. You can create your own strategy by implementing the ValidationStrategy
interface and providing a unique type
property. Then, register the strategy using the addStrategies
method before creating a Validator
instance.
import { ValidationStrategy, Validator } from "js-easy-validator";
class MyCustomValidationStrategy implements ValidationStrategy {
type = "myCustomValidation";
validate(rule, value) {
// Custom validation logic
}
}
Validator.addStrategies(new MyCustomValidationStrategy());
The Validator
package comes with the following default validation strategies:
__required
: Checks if the field is required.__regexp
: Validates the field against a regular expression pattern.__custom
: Executes a custom validation function.
You can extend the default strategies by subclassing the existing validation strategy classes. Override the validate
method with your custom validation logic, and register the new strategy using the addStrategies
method.
The main class representing the validator.
Creates a new Validator
instance with optional initial validation rules.
rules?: RuleItem[] // An optional array of validation rules.
Adds one or more validation rules to the Validator
.```typescript
rules?: RuleItem[] // An optional array of validation rules.
#### `add(...rules: RuleItem[])`
Adds one or more validation rules to the `Validator`.
- `...rules` (Rest parameter): The validation rules to add.
#### `run(value: any): string`
Runs the validation process on a given value and returns the validation error message, if any.
- `value`: The value to validate.
### `RuleItem`
The type representing a validation rule item.
#### `RuleItemRequired`
Represents a required field validation rule.
```typescript
{
required: boolean; // Indicates if the field is required.
message?: string; // Optional error message for the validation rule.
}
Represents a regular expression pattern validation rule.
{
reg: RegExp; // The regular expression pattern to match against.
message?: string; // Optional error message for the validation rule.
}
Represents a custom validation function rule.
{
validator: (rule: RuleItem, value: any) => Error | void; // The custom validation function.
}
Represents additional field properties for a rule.
{
message?: string; // Optional error message for the validation rule.
type?: string; // Optional field type for custom validation strategies.
}
The interface representing a validation strategy.
A unique identifier for the validation strategy.
Performs the validation based on the provided rule and value. It returns void
if the validation is successful or a validation error message as a string
if the validation fails.
A static property containing the default validation strategies provided by the package.
Adds additional validation strategies to the Validator
.
...ValidationStrategy
(Rest parameter): The validation strategies to add.
import { Validator } from "js-easy-validator";
const rules = [
{ required: true, message: "Field is required" },
{ reg: /^[A-Z]+$/, message: "Field should contain uppercase letters only" },
];
const validator = new Validator(rules);
const value = "ABC";
const errorMessage = validator.run(value);
if (errorMessage) {
console.error(errorMessage);
} else {
console.log("Value is valid");
}
import { Validator, ValidationStrategy } from "js-easy-validator";
class MyCustomValidationStrategy implements ValidationStrategy {
type = "myCustomValidation";
validate(rule, value) {
// Custom validation logic
}
}
Validator.addStrategies(new MyCustomValidationStrategy());
const rules = [
{ type: "myCustomValidation", message: "Custom validation failed" },
];
const validator = new Validator(rules);
const value = "ABC";
const errorMessage = validator.run(value);
if (errorMessage) {
console.error(errorMessage);
} else {
console.log("Value is valid");
}
This project is licensed under the MIT License - see the LICENSE file for details.