Bean Validator
A flexible and powerful validation library for Node.js that allows you to validate JavaScript objects through rule-based validation.
中文文档 | English
Installation
npm i @ticatec/bean-validator
Quick Start
import beanValidator from "@ticatec/bean-validator";
import {BaseValidator, StringValidator, NumberValidator, DateValidator, EnumValidator, ObjectValidator, ArrayValidator} from "@ticatec/bean-validator";
// Define validation rules
let rules: Array<BaseValidator> = [
new StringValidator('name', {required: true, maxLen: 50}),
new NumberValidator('age', {required: true, minValue: 0, maxValue: 120}),
new EnumValidator('gender', {values: ['M', 'F', 'Other']})
];
// Data to validate
let data = {
name: 'John Doe',
age: 30,
gender: 'M'
};
// Perform validation
let result = beanValidator.validate(data, rules);
if (result.valid) {
console.log('Validation passed!');
} else {
console.log('Validation errors:', result.errorMessage);
}
Validators
StringValidator
Validates string values with support for length constraints and format validation.
Constructor
interface StringValidatorOptions extends ValidatorOptions {
minLen?: number, // Minimum length
maxLen?: number, // Maximum length
format?: {
regex: RegExp, // Regular expression for format validation
message: string // Error message when format validation fails
}
}
new StringValidator(field: string, options?: StringValidatorOptions);
Example
new StringValidator('email', {
required: true,
maxLen: 100,
format: {
regex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
message: 'Invalid email format'
}
});
NumberValidator
Validates numeric values with range constraints and automatic type conversion.
Constructor
interface NumberValidatorOptions extends ValidatorOptions {
minValue?: number, // Minimum value
maxValue?: number, // Maximum value
}
new NumberValidator(field: string, options?: NumberValidatorOptions);
Example
new NumberValidator('age', {
required: true,
minValue: 0,
maxValue: 120
});
DateValidator
Validates date values with support for date ranges and relative date constraints.
Constructor
interface DateValidatorOptions extends ValidatorOptions {
from?: Date, // Earliest allowed date
to?: Date, // Latest allowed date
maxDaysBefore?: number, // Maximum days before today
maxDaysAfter?: number, // Maximum days after today
}
new DateValidator(field: string, options?: DateValidatorOptions);
Example
new DateValidator('birthDate', {
required: true,
maxDaysBefore: 36500 // Allow dates up to 100 years ago
});
EnumValidator
Validates that a value exists within a predefined set of allowed values.
Constructor
interface EnumValidatorOptions extends ValidatorOptions {
values: Array<any>; // Array of allowed values
}
new EnumValidator(field: string, options: EnumValidatorOptions);
Example
new EnumValidator('status', {
required: true,
values: ['active', 'inactive', 'pending']
});
BooleanValidator
Validates boolean values with automatic type conversion.
Constructor
interface BooleanValidatorOptions extends ValidatorOptions {
// No additional options beyond base ValidatorOptions
}
new BooleanValidator(field: string, options?: BooleanValidatorOptions);
ObjectValidator
Validates nested objects by applying a set of validation rules to the object's properties.
Constructor
interface ObjectValidatorOptions extends ValidatorOptions {
rules: Array<BaseValidator>; // Validation rules for the nested object
}
new ObjectValidator(field: string, options: ObjectValidatorOptions);
Example
let addressRules = [
new StringValidator('street', {required: true, maxLen: 100}),
new StringValidator('city', {required: true, maxLen: 50}),
new StringValidator('zipCode', {required: true, maxLen: 10})
];
new ObjectValidator('address', {
required: true,
rules: addressRules
});
ArrayValidator
Validates arrays with support for length constraints and element validation.
Constructor
interface ArrayValidatorOptions extends ValidatorOptions {
rules?: Array<BaseValidator>; // Validation rules for array elements
minLen?: number; // Minimum array length
maxLen?: number; // Maximum array length
}
new ArrayValidator(field: string, options?: ArrayValidatorOptions);
Example
let itemRules = [
new StringValidator('name', {required: true}),
new NumberValidator('quantity', {required: true, minValue: 1})
];
new ArrayValidator('items', {
required: true,
minLen: 1,
maxLen: 10,
rules: itemRules
});
Common Options
All validators extend from BaseValidator
and support these common options:
interface ValidatorOptions {
required?: boolean; // Whether the field is required
check?: CustomCheck; // Custom validation function
}
type CustomCheck = (value: any, data: any, prefix: string) => string | null;
Custom Validation
You can add custom validation logic using the check
option:
new StringValidator('username', {
required: true,
minLen: 3,
maxLen: 20,
check: (value, data, prefix) => {
if (value.includes(' ')) {
return 'Username cannot contain spaces';
}
return null; // null means validation passed
}
});
Advanced Features
Nested Field Access
The library supports dot notation for accessing nested properties:
new StringValidator('user.profile.name', {required: true});
Type Conversion
The library automatically converts compatible types:
- String numbers to actual numbers in NumberValidator
- String representations to proper types where applicable
Error Handling
Validation results provide detailed error information:
let result = beanValidator.validate(data, rules);
if (!result.valid) {
console.log('All errors:', result.errorMessage);
// Errors are joined with newlines
}
Complete Example
import beanValidator from "@ticatec/bean-validator";
import {BaseValidator, StringValidator, NumberValidator, DateValidator, EnumValidator, ObjectValidator, ArrayValidator} from "@ticatec/bean-validator";
// Define rules for member object
let memberRules: Array<BaseValidator> = [
new DateValidator('registerOn', {maxDaysAfter: -5}),
new StringValidator('password', {
required: true,
format: {
regex: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{8,}$/,
message: 'Password must be at least 8 characters with uppercase, lowercase and numbers'
}
})
];
// Define main validation rules
let rules: Array<BaseValidator> = [
new StringValidator('name', {required: true, maxLen: 50}),
new NumberValidator('age', {required: true, maxValue: 90, minValue: 15}),
new DateValidator('dob', {maxDaysBefore: 100000}),
new EnumValidator('gender', {values: ['F', 'M']}),
new ObjectValidator('member', {rules: memberRules})
];
// Rules for parent with children
let parentRules: Array<BaseValidator> = [
...rules,
new ArrayValidator('children', {required: true, rules: rules})
];
let data = {
name: 'John Doe',
age: 35,
dob: '1988-03-05',
gender: 'M',
member: {
registerOn: new Date('2023-01-01'),
password: 'SecurePass123'
},
children: [
{
name: 'Jane',
age: 16,
dob: '2007-08-12',
gender: 'F',
member: {
registerOn: new Date('2023-06-01'),
password: 'ChildPass456'
}
}
]
};
let result = beanValidator.validate(data, parentRules);
if (result.valid) {
console.log('All validations passed!');
console.log('Validated data:', data);
} else {
console.log('Validation errors:');
console.log(result.errorMessage);
}
License
MIT
Repository
- GitHub: https://github.com/ticatec/node-library
- Issues: https://github.com/ticatec/bean-validator/issues
Author
Henry Feng