snap-validate 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +278 -0
- package/package.json +86 -0
- package/src/index.js +236 -0
- package/src/validators/index.js +0 -0
- package/types/index.d.ts +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Mini Validator Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
# Snap Validate โก
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/js/snap-validate)
|
|
4
|
+
[](https://github.com/aniru-dh21/snap-validate/actions)
|
|
5
|
+
[](https://codecov.io/gh/aniru-dh21/snap-validate)
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
|
|
8
|
+
A lightning-fast, lightweight validation library for common patterns without heavy dependencies. Perfect for client-side and server-side validation with zero external dependencies.
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- โก **Lightning Fast**: Optimized for speed and performance
|
|
13
|
+
- ๐ **Lightweight**: No external dependencies, minimal footprint
|
|
14
|
+
- ๐ง **Flexible**: Chainable validation rules and custom validators
|
|
15
|
+
- ๐ง **Common Patterns**: Email, phone, credit card, URL, password validation
|
|
16
|
+
- ๐ **International**: Support for different formats (US/International phone, postal codes)
|
|
17
|
+
- ๐งช **Well Tested**: Comprehensive test suite with high coverage
|
|
18
|
+
- ๐ฆ **Easy Integration**: Works in Node.js and browsers
|
|
19
|
+
- ๐ **Chainable API**: Intuitive fluent interface
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install snap-validate
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Quick Start
|
|
28
|
+
|
|
29
|
+
```javascript
|
|
30
|
+
const { validators, validate } = require('snap-validate');
|
|
31
|
+
|
|
32
|
+
// Single field validation
|
|
33
|
+
const emailResult = validators.email('user@example.com').validate();
|
|
34
|
+
console.log(emailResult.isValid); // true
|
|
35
|
+
|
|
36
|
+
// Schema validation
|
|
37
|
+
const schema = {
|
|
38
|
+
email: validators.email,
|
|
39
|
+
phone: (value) => validators.phone(value, 'us'),
|
|
40
|
+
password: validators.password
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const data = {
|
|
44
|
+
email: 'user@example.com',
|
|
45
|
+
phone: '(555) 123-4567',
|
|
46
|
+
password: 'SecurePass123'
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const result = validate(schema, data);
|
|
50
|
+
console.log(result.isValid); // true
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Available Validators
|
|
54
|
+
|
|
55
|
+
### Email Validation
|
|
56
|
+
|
|
57
|
+
```javascript
|
|
58
|
+
validators.email('user@example.com').validate();
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### Phone Number Validation
|
|
62
|
+
|
|
63
|
+
```javascript
|
|
64
|
+
// US format (default)
|
|
65
|
+
validators.phone('(555) 123-4567').validate();
|
|
66
|
+
|
|
67
|
+
// International format
|
|
68
|
+
validators.phone('+1234567890', 'international').validate();
|
|
69
|
+
|
|
70
|
+
// Simple numeric
|
|
71
|
+
validators.phone('1234567890', 'simple').validate();
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Credit Card Validation
|
|
75
|
+
|
|
76
|
+
```javascript
|
|
77
|
+
// Uses Luhn algorithm
|
|
78
|
+
validators.creditCard('4532015112830366').validate();
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### URL Validation
|
|
82
|
+
|
|
83
|
+
```javascript
|
|
84
|
+
validators.url('https://example.com').validate();
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### Password Validation
|
|
88
|
+
|
|
89
|
+
```javascript
|
|
90
|
+
// Default: min 8 chars, requires upper, lower, numbers
|
|
91
|
+
validators.password('SecurePass123').validate();
|
|
92
|
+
|
|
93
|
+
// Custom options
|
|
94
|
+
validators.password('MyPass123!', {
|
|
95
|
+
minLength: 10,
|
|
96
|
+
requireUppercase: true,
|
|
97
|
+
requireLowercase: true,
|
|
98
|
+
requireNumbers: true,
|
|
99
|
+
requireSpecialChars: true
|
|
100
|
+
}).validate();
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Alphanumeric Validation
|
|
104
|
+
|
|
105
|
+
```javascript
|
|
106
|
+
validators.alphanumeric('ABC123').validate();
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Numeric Validation
|
|
110
|
+
|
|
111
|
+
```javascript
|
|
112
|
+
validators.numeric('12345').validate();
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Zip Code Validation
|
|
116
|
+
|
|
117
|
+
```javascript
|
|
118
|
+
// US zip code
|
|
119
|
+
validators.zipCode('12345').validate();
|
|
120
|
+
validators.zipCode('12345-6789').validate();
|
|
121
|
+
|
|
122
|
+
// Canadian postal code
|
|
123
|
+
validators.zipCode('K1A 0A6', 'ca').validate();
|
|
124
|
+
|
|
125
|
+
// UK postal code
|
|
126
|
+
validators.zipCode('SW1A 1AA', 'uk').validate();
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
## Custom Validation
|
|
130
|
+
|
|
131
|
+
### Using BaseValidator
|
|
132
|
+
|
|
133
|
+
```javascript
|
|
134
|
+
const { BaseValidator } = require('snap-validate');
|
|
135
|
+
|
|
136
|
+
const customValidator = new BaseValidator('test-value')
|
|
137
|
+
.required('This field is required')
|
|
138
|
+
.min(5, 'Must be at least 5 characters')
|
|
139
|
+
.max(20, 'Must be no more than 20 characters')
|
|
140
|
+
.pattern(/^[a-zA-Z]+$/, 'Only letters allowed');
|
|
141
|
+
|
|
142
|
+
const result = customValidator.validate();
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Schema Validation with Custom Rules
|
|
146
|
+
|
|
147
|
+
```javascript
|
|
148
|
+
const schema = {
|
|
149
|
+
username: (value) => new BaseValidator(value)
|
|
150
|
+
.required()
|
|
151
|
+
.min(3)
|
|
152
|
+
.max(20)
|
|
153
|
+
.pattern(/^[a-zA-Z0-9_]+$/, 'Username can only contain letters, numbers, and underscores'),
|
|
154
|
+
|
|
155
|
+
email: validators.email,
|
|
156
|
+
|
|
157
|
+
age: (value) => new BaseValidator(value)
|
|
158
|
+
.required()
|
|
159
|
+
.pattern(/^\d+$/, 'Age must be a number')
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
const userData = {
|
|
163
|
+
username: 'john_doe',
|
|
164
|
+
email: 'john@example.com',
|
|
165
|
+
age: '25'
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const result = validate(schema, userData);
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Error Handling
|
|
172
|
+
|
|
173
|
+
```javascript
|
|
174
|
+
const result = validators.email('invalid-email').validate();
|
|
175
|
+
|
|
176
|
+
if (!result.isValid) {
|
|
177
|
+
console.log('Validation errors:', result.errors);
|
|
178
|
+
// Output: ['Invalid email format']
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// For schema validation
|
|
182
|
+
const schemaResult = validate(schema, data);
|
|
183
|
+
if (!schemaResult.isValid) {
|
|
184
|
+
const errors = schemaResult.getErrors();
|
|
185
|
+
console.log('Field errors:', errors);
|
|
186
|
+
// Output: { email: ['Invalid email format'], password: ['Password too weak'] }
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Browser Usage
|
|
191
|
+
|
|
192
|
+
```html
|
|
193
|
+
<script src="https://unpkg.com/snap-validate/src/index.js"></script>
|
|
194
|
+
<script>
|
|
195
|
+
const { validators } = SnapValidate;
|
|
196
|
+
|
|
197
|
+
const result = validators.email('user@example.com').validate();
|
|
198
|
+
console.log(result.isValid);
|
|
199
|
+
</script>
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## API Reference
|
|
203
|
+
|
|
204
|
+
### ValidationResult
|
|
205
|
+
|
|
206
|
+
- `isValid: boolean` - Whether validation passed
|
|
207
|
+
- `errors: string[]` - Array of error messages
|
|
208
|
+
|
|
209
|
+
### BaseValidator Methods
|
|
210
|
+
|
|
211
|
+
- `required(message?)` - Field is required
|
|
212
|
+
- `min(length, message?)` - Minimum length validation
|
|
213
|
+
- `max(length, message?)` - Maximum length validation
|
|
214
|
+
- `pattern(regex, message?)` - Pattern matching validation
|
|
215
|
+
- `validate()` - Execute validation and return result
|
|
216
|
+
|
|
217
|
+
### Available Validators
|
|
218
|
+
|
|
219
|
+
- `validators.email(value)`
|
|
220
|
+
- `validators.phone(value, format?)`
|
|
221
|
+
- `validators.creditCard(value)`
|
|
222
|
+
- `validators.url(value)`
|
|
223
|
+
- `validators.password(value, options?)`
|
|
224
|
+
- `validators.alphanumeric(value)`
|
|
225
|
+
- `validators.numeric(value)`
|
|
226
|
+
- `validators.zipCode(value, country?)`
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
## Contributing
|
|
230
|
+
|
|
231
|
+
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
|
|
232
|
+
|
|
233
|
+
1. Fork the repository
|
|
234
|
+
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
|
235
|
+
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
|
|
236
|
+
4. Push to the branch (`git push origin feature/amazing-feature`)
|
|
237
|
+
5. Open a Pull Request
|
|
238
|
+
|
|
239
|
+
## Development
|
|
240
|
+
|
|
241
|
+
```bash
|
|
242
|
+
# Install dependencies
|
|
243
|
+
npm install
|
|
244
|
+
|
|
245
|
+
# Run tests
|
|
246
|
+
npm test
|
|
247
|
+
|
|
248
|
+
# Run tests in watch mode
|
|
249
|
+
npm run test:watch
|
|
250
|
+
|
|
251
|
+
# Run tests with coverage
|
|
252
|
+
npm run test:coverage
|
|
253
|
+
|
|
254
|
+
# Lint code
|
|
255
|
+
npm run lint
|
|
256
|
+
|
|
257
|
+
# Format code
|
|
258
|
+
npm run format
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
## License
|
|
262
|
+
|
|
263
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
264
|
+
|
|
265
|
+
## Changelog
|
|
266
|
+
|
|
267
|
+
### v1.0.0
|
|
268
|
+
|
|
269
|
+
- Initial release
|
|
270
|
+
- Basic validation patterns (email, phone, credit card, URL, password)
|
|
271
|
+
- Schema validation support
|
|
272
|
+
- Comprehensive test suite
|
|
273
|
+
- CI/CD pipeline setup
|
|
274
|
+
- Lightning-fast performance optimizations
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
Made with โก by [Ramachandra Anirudh Vemulapalli](https://github.com/aniru-dh21)
|
package/package.json
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "snap-validate",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Lightweight validation library for common patterns without heavy dependencies",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"types": "types/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "jest",
|
|
9
|
+
"test:watch": "jest --watch",
|
|
10
|
+
"test:coverage": "jest --coverage",
|
|
11
|
+
"lint": "eslint src tests",
|
|
12
|
+
"lint:fix": "eslint src tests --fix",
|
|
13
|
+
"format": "prettier --write \"src/**/*.js\" \"tests/**/*.js\"",
|
|
14
|
+
"prepare": "husky install",
|
|
15
|
+
"prepublishOnly": "npm test && npm run lint",
|
|
16
|
+
"build": "echo 'No build step required for this library'",
|
|
17
|
+
"example": "node examples/basic-usage.js"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"validation",
|
|
21
|
+
"validator",
|
|
22
|
+
"lightweight",
|
|
23
|
+
"snap",
|
|
24
|
+
"quick",
|
|
25
|
+
"fast",
|
|
26
|
+
"email",
|
|
27
|
+
"phone",
|
|
28
|
+
"credit-card",
|
|
29
|
+
"url",
|
|
30
|
+
"password",
|
|
31
|
+
"forms",
|
|
32
|
+
"input-validation",
|
|
33
|
+
"schema-validation",
|
|
34
|
+
"pattern-matching"
|
|
35
|
+
],
|
|
36
|
+
"author": "Ramachandra Anirudh Vemulapalli",
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/aniru-dh21/snap-validate.git"
|
|
41
|
+
},
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/aniru-dh21/snap-validate/issues"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/aniru-dh21/snap-validate#readme",
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@babel/core": "^7.24.0",
|
|
48
|
+
"@babel/preset-env": "^7.24.0",
|
|
49
|
+
"babel-jest": "^29.7.0",
|
|
50
|
+
"eslint": "^8.57.1",
|
|
51
|
+
"husky": "^9.1.0",
|
|
52
|
+
"jest": "^29.7.0",
|
|
53
|
+
"lint-staged": "^15.2.0",
|
|
54
|
+
"prettier": "^3.2.0"
|
|
55
|
+
},
|
|
56
|
+
"files": [
|
|
57
|
+
"src/",
|
|
58
|
+
"types/",
|
|
59
|
+
"README.md",
|
|
60
|
+
"LICENSE"
|
|
61
|
+
],
|
|
62
|
+
"engines": {
|
|
63
|
+
"node": ">=12.0.0"
|
|
64
|
+
},
|
|
65
|
+
"jest": {
|
|
66
|
+
"testEnvironment": "node",
|
|
67
|
+
"collectCoverageFrom": [
|
|
68
|
+
"src/**/*.js",
|
|
69
|
+
"!src/**/*.test.js"
|
|
70
|
+
],
|
|
71
|
+
"coverageThreshold": {
|
|
72
|
+
"global": {
|
|
73
|
+
"branches": 80,
|
|
74
|
+
"functions": 80,
|
|
75
|
+
"lines": 80,
|
|
76
|
+
"statements": 80
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
"lint-staged": {
|
|
81
|
+
"*.js": [
|
|
82
|
+
"eslint --fix",
|
|
83
|
+
"prettier --write"
|
|
84
|
+
]
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Snap Validate - Lightweight validator library
|
|
3
|
+
* @version 0.0.1
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// Core validation class
|
|
7
|
+
class ValidationResult {
|
|
8
|
+
constructor(isValid, errors = []) {
|
|
9
|
+
this.isValid = isValid;
|
|
10
|
+
this.errors = errors;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
addError(message) {
|
|
14
|
+
this.errors.push(message);
|
|
15
|
+
this.isValid = false;
|
|
16
|
+
return this;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Base validator class
|
|
21
|
+
class BaseValidator {
|
|
22
|
+
constructor(value) {
|
|
23
|
+
this.value = value;
|
|
24
|
+
this.rules = [];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
required(message = 'This field is required') {
|
|
28
|
+
this.rules.push(() => {
|
|
29
|
+
if (this.value === null || this.value === undefined || this.value === '') {
|
|
30
|
+
return new ValidationResult(false, [message]);
|
|
31
|
+
}
|
|
32
|
+
return new ValidationResult(true);
|
|
33
|
+
});
|
|
34
|
+
return this;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
min(length, message = `Minimum length is ${length}`) {
|
|
38
|
+
this.rules.push(() => {
|
|
39
|
+
if (this.value && this.value.length < length) {
|
|
40
|
+
return new ValidationResult(false, [message]);
|
|
41
|
+
}
|
|
42
|
+
return new ValidationResult(true);
|
|
43
|
+
});
|
|
44
|
+
return this;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
max(length, message = `Maximum length is ${length}`) {
|
|
48
|
+
this.rules.push(() => {
|
|
49
|
+
if (this.value && this.value.length > length) {
|
|
50
|
+
return new ValidationResult(false, [message]);
|
|
51
|
+
}
|
|
52
|
+
return new ValidationResult(true);
|
|
53
|
+
});
|
|
54
|
+
return this;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
pattern(regex, message = 'Invalid format') {
|
|
58
|
+
this.rules.push(() => {
|
|
59
|
+
if (this.value && !regex.test(this.value)) {
|
|
60
|
+
return new ValidationResult(false, [message]);
|
|
61
|
+
}
|
|
62
|
+
return new ValidationResult(true);
|
|
63
|
+
});
|
|
64
|
+
return this;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
validate() {
|
|
68
|
+
const result = new ValidationResult(true);
|
|
69
|
+
|
|
70
|
+
for (const rule of this.rules) {
|
|
71
|
+
const ruleResult = rule();
|
|
72
|
+
if (!ruleResult.isValid) {
|
|
73
|
+
result.isValid = false;
|
|
74
|
+
result.errors.push(...ruleResult.errors);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Predefined validators
|
|
83
|
+
const validators = {
|
|
84
|
+
email: (value) => {
|
|
85
|
+
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
86
|
+
return new BaseValidator(value)
|
|
87
|
+
.required('Email is required')
|
|
88
|
+
.pattern(emailRegex, 'Invalid email format');
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
phone: (value, format = 'us') => {
|
|
92
|
+
const phoneRegex = {
|
|
93
|
+
us: /^\+?1?[-.\s]?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$/,
|
|
94
|
+
international: /^\+[1-9]\d{1,14}$/,
|
|
95
|
+
simple: /^\d{10,15}$/
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
return new BaseValidator(value)
|
|
99
|
+
.required('Phone number is required')
|
|
100
|
+
.pattern(phoneRegex[format] || phoneRegex.simple, 'Invalid phone number format');
|
|
101
|
+
},
|
|
102
|
+
|
|
103
|
+
creditCard: (value) => {
|
|
104
|
+
// Luhn algorithm check
|
|
105
|
+
const luhnCheck = (num) => {
|
|
106
|
+
let sum = 0;
|
|
107
|
+
let isEven = false;
|
|
108
|
+
|
|
109
|
+
for (let i = num.length - 1; i >= 0; i--) {
|
|
110
|
+
let digit = parseInt(num[i]);
|
|
111
|
+
|
|
112
|
+
if (isEven) {
|
|
113
|
+
digit *= 2;
|
|
114
|
+
if (digit > 9) digit -= 9;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
sum += digit;
|
|
118
|
+
isEven = !isEven;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return sum % 10 === 0;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const validator = new BaseValidator(value)
|
|
125
|
+
.required('Credit card number is required')
|
|
126
|
+
.pattern(/^\d{13,19}$/, 'Credit card must be 13-19 digits');
|
|
127
|
+
|
|
128
|
+
validator.rules.push(() => {
|
|
129
|
+
if (value && !luhnCheck(value.replace(/\s/g, ''))) {
|
|
130
|
+
return new ValidationResult(false, ['Invalid credit card number']);
|
|
131
|
+
}
|
|
132
|
+
return new ValidationResult(true);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
return validator;
|
|
136
|
+
},
|
|
137
|
+
|
|
138
|
+
url: (value) => {
|
|
139
|
+
const urlRegex = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;
|
|
140
|
+
return new BaseValidator(value)
|
|
141
|
+
.required('URL is required')
|
|
142
|
+
.pattern(urlRegex, 'Invalid URL format');
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
password: (value, options = {}) => {
|
|
146
|
+
const {
|
|
147
|
+
minLength = 8,
|
|
148
|
+
requireUppercase = true,
|
|
149
|
+
requireLowercase = true,
|
|
150
|
+
requireNumbers = true,
|
|
151
|
+
requireSpecialChars = false
|
|
152
|
+
} = options;
|
|
153
|
+
|
|
154
|
+
const validator = new BaseValidator(value)
|
|
155
|
+
.required('Password is required')
|
|
156
|
+
.min(minLength, `Password must be at least ${minLength} characters`);
|
|
157
|
+
|
|
158
|
+
if (requireUppercase) {
|
|
159
|
+
validator.pattern(/[A-Z]/, 'Password must contain at least one uppercase letter');
|
|
160
|
+
}
|
|
161
|
+
if (requireLowercase) {
|
|
162
|
+
validator.pattern(/[a-z]/, 'Password must contain at least one lowercase letter');
|
|
163
|
+
}
|
|
164
|
+
if (requireNumbers) {
|
|
165
|
+
validator.pattern(/\d/, 'Password must contain at least one number');
|
|
166
|
+
}
|
|
167
|
+
if (requireSpecialChars) {
|
|
168
|
+
validator.pattern(/[!@#$%^&*(),.?":{}|<>]/, 'Password must contain at least one special character');
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return validator;
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
alphanumeric: (value) => {
|
|
175
|
+
return new BaseValidator(value)
|
|
176
|
+
.required('This field is required')
|
|
177
|
+
.pattern(/^[a-zA-Z0-9]+$/, 'Only letters and number are allowed');
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
numeric: (value) => {
|
|
181
|
+
return new BaseValidator(value)
|
|
182
|
+
.required('This field is required')
|
|
183
|
+
.pattern(/^\d+$/, 'Only numbers are allowed');
|
|
184
|
+
},
|
|
185
|
+
|
|
186
|
+
zipCode: (value, country = 'us') => {
|
|
187
|
+
const zipRegex = {
|
|
188
|
+
us: /^\d{5}(-\d{4})?$/,
|
|
189
|
+
ca: /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/,
|
|
190
|
+
uk: /^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/i
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
return new BaseValidator(value)
|
|
194
|
+
.required('Zip code is required')
|
|
195
|
+
.pattern(zipRegex[country] || zipRegex.us, 'Invalid zip code format');
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// Main validation function
|
|
200
|
+
const validate = (schema, data) => {
|
|
201
|
+
const results = {};
|
|
202
|
+
let isValid = true;
|
|
203
|
+
|
|
204
|
+
for (const [field, validator] of Object.entries(schema)) {
|
|
205
|
+
const fieldValue = data[field];
|
|
206
|
+
const result = typeof validator === 'function'
|
|
207
|
+
? validator(fieldValue).validate()
|
|
208
|
+
: validator.validate();
|
|
209
|
+
|
|
210
|
+
results[field] = result;
|
|
211
|
+
if (!result.isValid) {
|
|
212
|
+
isValid = false;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return {
|
|
217
|
+
isValid,
|
|
218
|
+
errors: results,
|
|
219
|
+
getErrors: () => {
|
|
220
|
+
const errors = {};
|
|
221
|
+
for (const [field, result] of Object.entries(results)) {
|
|
222
|
+
if (!result.isValid) {
|
|
223
|
+
errors[field] = result.errors;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return errors;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
module.exports = {
|
|
232
|
+
BaseValidator,
|
|
233
|
+
ValidationResult,
|
|
234
|
+
validators,
|
|
235
|
+
validate
|
|
236
|
+
};
|
|
File without changes
|
package/types/index.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
declare module 'mini-validator' {
|
|
2
|
+
export interface ValidationResult {
|
|
3
|
+
isValid: boolean;
|
|
4
|
+
errors: string[];
|
|
5
|
+
addError(message: string): ValidationResult;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface PasswordOptions {
|
|
9
|
+
minLength?: number;
|
|
10
|
+
requireUppercase?: boolean;
|
|
11
|
+
requireLowercase?: boolean;
|
|
12
|
+
requireNumbers?: boolean;
|
|
13
|
+
requireSpecialChars?: boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type PhoneFormat = 'us' | 'international' | 'simple';
|
|
17
|
+
export type CountryCode = 'us' | 'ca' | 'uk';
|
|
18
|
+
|
|
19
|
+
export class BaseValidator {
|
|
20
|
+
constructor(value: any);
|
|
21
|
+
required(message?: string): BaseValidator;
|
|
22
|
+
min(length: number, message?: string): BaseValidator;
|
|
23
|
+
max(length: number, message?: string): BaseValidator;
|
|
24
|
+
pattern(regex: RegExp, message?: string): BaseValidator;
|
|
25
|
+
validate(): ValidationResult;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class ValidationResult {
|
|
29
|
+
constructor(isValid: boolean, errors?: string[]);
|
|
30
|
+
isValid: boolean;
|
|
31
|
+
errors: string[];
|
|
32
|
+
addError(message: string): ValidationResult;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface Validators {
|
|
36
|
+
email(value: string): BaseValidator;
|
|
37
|
+
phone(value: string, format?: PhoneFormat): BaseValidator;
|
|
38
|
+
creditCard(value: string): BaseValidator;
|
|
39
|
+
url(value: string): BaseValidator;
|
|
40
|
+
password(value: string, options?: PasswordOptions): BaseValidator;
|
|
41
|
+
alphanumeric(value: string): BaseValidator;
|
|
42
|
+
numeric(value: string): BaseValidator;
|
|
43
|
+
zipCode(value: string, country?: CountryCode): BaseValidator;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface SchemaValidationResult {
|
|
47
|
+
isValid: boolean;
|
|
48
|
+
errors: { [field: string]: ValidationResult };
|
|
49
|
+
getErrors(): { [field: string]: string[] };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type ValidationFunction = (value: any) => BaseValidator;
|
|
53
|
+
export type Schema = { [field: string]: ValidationFunction };
|
|
54
|
+
|
|
55
|
+
export const validators: Validators;
|
|
56
|
+
export function validate(
|
|
57
|
+
schema: Schema,
|
|
58
|
+
data: { [key: string]: any }
|
|
59
|
+
): SchemaValidationResult;
|
|
60
|
+
}
|