phani-validations 0.0.0-stage → 1.0.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.
@@ -0,0 +1,98 @@
1
+ const LOCAL_PART_REGEX = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+$/;
2
+ const DOMAIN_LABEL_REGEX = /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;
3
+ const TLD_REGEX = /^[a-zA-Z]{2,}$/;
4
+
5
+ /**
6
+ * Validates an email address and returns detailed validation errors.
7
+ *
8
+ * @param {unknown} value - The email value to validate.
9
+ * @param {object} [options]
10
+ * @param {boolean} [options.trim=false] - Whether to trim leading/trailing whitespace before validating.
11
+ * @param {string[]} [options.allowedDomains] - Whitelist of allowed email domains (case-insensitive).
12
+ * @param {string[]} [options.blockedDomains] - Blacklist of blocked email domains (case-insensitive).
13
+ * @returns {{ valid: boolean, errors: string[] }}
14
+ */
15
+ export function validateEmail(value, options = {}) {
16
+ const { trim = false, allowedDomains, blockedDomains } = options;
17
+ const errors = [];
18
+
19
+ if (typeof value !== 'string') {
20
+ return { valid: false, errors: ['Email must be a string.'] };
21
+ }
22
+
23
+ const email = trim ? value.trim() : value;
24
+
25
+ if (email.length === 0) {
26
+ return { valid: false, errors: ['Email is required.'] };
27
+ }
28
+
29
+ if (email.length > 254) {
30
+ errors.push('Email must not exceed 254 characters.');
31
+ }
32
+
33
+ if (/\s/.test(email)) {
34
+ errors.push('Email must not contain whitespace.');
35
+ }
36
+
37
+ const parts = email.split('@');
38
+ if (parts.length !== 2) {
39
+ return { valid: false, errors: [...errors, 'Email must contain a single "@" symbol.'] };
40
+ }
41
+
42
+ const [localPart, domain] = parts;
43
+
44
+ if (localPart.length === 0 || localPart.length > 64) {
45
+ errors.push('Email local part must be between 1 and 64 characters.');
46
+ } else if (
47
+ localPart.startsWith('.') ||
48
+ localPart.endsWith('.') ||
49
+ localPart.includes('..') ||
50
+ !LOCAL_PART_REGEX.test(localPart)
51
+ ) {
52
+ errors.push('Email local part contains invalid characters or dot placement.');
53
+ }
54
+
55
+ if (domain.length === 0 || domain.length > 255) {
56
+ errors.push('Email domain must be between 1 and 255 characters.');
57
+ } else {
58
+ const labels = domain.split('.');
59
+ if (labels.length < 2) {
60
+ errors.push('Email domain must include a valid top-level domain.');
61
+ } else {
62
+ const tld = labels[labels.length - 1];
63
+ const allLabelsValid = labels.every((label) => DOMAIN_LABEL_REGEX.test(label));
64
+ if (!allLabelsValid || !TLD_REGEX.test(tld)) {
65
+ errors.push('Email domain format is invalid.');
66
+ }
67
+ }
68
+ }
69
+
70
+ const normalizedDomain = domain.toLowerCase();
71
+
72
+ if (Array.isArray(allowedDomains) && allowedDomains.length > 0) {
73
+ const allowed = allowedDomains.map((d) => String(d).toLowerCase());
74
+ if (!allowed.includes(normalizedDomain)) {
75
+ errors.push(`Email domain "${domain}" is not allowed.`);
76
+ }
77
+ }
78
+
79
+ if (Array.isArray(blockedDomains) && blockedDomains.length > 0) {
80
+ const blocked = blockedDomains.map((d) => String(d).toLowerCase());
81
+ if (blocked.includes(normalizedDomain)) {
82
+ errors.push(`Email domain "${domain}" is blocked.`);
83
+ }
84
+ }
85
+
86
+ return { valid: errors.length === 0, errors };
87
+ }
88
+
89
+ /**
90
+ * Checks whether a value is a valid email address.
91
+ *
92
+ * @param {unknown} value
93
+ * @param {object} [options]
94
+ * @returns {boolean}
95
+ */
96
+ export function isEmail(value, options) {
97
+ return validateEmail(value, options).valid;
98
+ }
@@ -0,0 +1,160 @@
1
+ import {
2
+ hasUppercase,
3
+ hasLowercase,
4
+ hasDigits,
5
+ hasSpecialChars,
6
+ hasSpaces,
7
+ } from './characters.js';
8
+
9
+ /**
10
+ * Evaluates password strength independent of custom rule overrides.
11
+ *
12
+ * @param {unknown} value
13
+ * @returns {'weak' | 'medium' | 'strong'}
14
+ */
15
+ export function getPasswordStrength(value) {
16
+ if (typeof value !== 'string' || value.length < 6) {
17
+ return 'weak';
18
+ }
19
+
20
+ let score = 0;
21
+ if (value.length >= 8) score += 1;
22
+ if (value.length >= 12) score += 1;
23
+ if (hasUppercase(value)) score += 1;
24
+ if (hasLowercase(value)) score += 1;
25
+ if (hasDigits(value)) score += 1;
26
+ if (hasSpecialChars(value)) score += 1;
27
+
28
+ if (score >= 5 && value.length >= 8) {
29
+ return 'strong';
30
+ }
31
+ if (score >= 3) {
32
+ return 'medium';
33
+ }
34
+ return 'weak';
35
+ }
36
+
37
+ /**
38
+ * Validates a password against configurable complexity rules and returns detailed results.
39
+ *
40
+ * @param {unknown} value - The password string to validate.
41
+ * @param {object} [options]
42
+ * @param {number} [options.minLength=8] - Minimum password length.
43
+ * @param {number} [options.maxLength=128] - Maximum password length.
44
+ * @param {boolean} [options.requireUppercase=true] - Require at least one uppercase letter.
45
+ * @param {boolean} [options.requireLowercase=true] - Require at least one lowercase letter.
46
+ * @param {boolean} [options.requireDigits=true] - Require at least one digit (0-9).
47
+ * @param {boolean} [options.requireNumbers] - Alias for requireDigits.
48
+ * @param {boolean} [options.requireSpecialChars=true] - Require at least one special character.
49
+ * @param {string} [options.specialChars] - Optional custom set of allowed special characters.
50
+ * @param {boolean} [options.allowSpaces=false] - Whether whitespace characters are allowed.
51
+ * @returns {{
52
+ * valid: boolean,
53
+ * errors: string[],
54
+ * strength: 'weak' | 'medium' | 'strong',
55
+ * checks: {
56
+ * minLength: boolean,
57
+ * maxLength: boolean,
58
+ * uppercase: boolean,
59
+ * lowercase: boolean,
60
+ * digits: boolean,
61
+ * specialChars: boolean,
62
+ * noSpaces: boolean
63
+ * }
64
+ * }}
65
+ */
66
+ export function validatePassword(value, options = {}) {
67
+ const {
68
+ minLength = 8,
69
+ maxLength = 128,
70
+ requireUppercase = true,
71
+ requireLowercase = true,
72
+ requireDigits,
73
+ requireNumbers,
74
+ requireSpecialChars = true,
75
+ specialChars,
76
+ allowSpaces = false,
77
+ } = options;
78
+
79
+ const mustHaveDigits = requireDigits ?? requireNumbers ?? true;
80
+
81
+ if (typeof value !== 'string') {
82
+ return {
83
+ valid: false,
84
+ errors: ['Password must be a string.'],
85
+ strength: 'weak',
86
+ checks: {
87
+ minLength: false,
88
+ maxLength: false,
89
+ uppercase: false,
90
+ lowercase: false,
91
+ digits: false,
92
+ specialChars: false,
93
+ noSpaces: false,
94
+ },
95
+ };
96
+ }
97
+
98
+ const checks = {
99
+ minLength: value.length >= minLength,
100
+ maxLength: value.length <= maxLength,
101
+ uppercase: hasUppercase(value),
102
+ lowercase: hasLowercase(value),
103
+ digits: hasDigits(value),
104
+ specialChars: hasSpecialChars(value, specialChars),
105
+ noSpaces: !hasSpaces(value),
106
+ };
107
+
108
+ const errors = [];
109
+
110
+ if (!checks.minLength) {
111
+ errors.push(`Password must be at least ${minLength} characters long.`);
112
+ }
113
+ if (!checks.maxLength) {
114
+ errors.push(`Password must not exceed ${maxLength} characters.`);
115
+ }
116
+ if (requireUppercase && !checks.uppercase) {
117
+ errors.push('Password must contain at least one uppercase letter.');
118
+ }
119
+ if (requireLowercase && !checks.lowercase) {
120
+ errors.push('Password must contain at least one lowercase letter.');
121
+ }
122
+ if (mustHaveDigits && !checks.digits) {
123
+ errors.push('Password must contain at least one digit.');
124
+ }
125
+ if (requireSpecialChars && !checks.specialChars) {
126
+ errors.push('Password must contain at least one special character.');
127
+ }
128
+ if (!allowSpaces && !checks.noSpaces) {
129
+ errors.push('Password must not contain spaces.');
130
+ }
131
+
132
+ return {
133
+ valid: errors.length === 0,
134
+ errors,
135
+ strength: getPasswordStrength(value),
136
+ checks,
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Checks whether a password satisfies the configured validation rules.
142
+ *
143
+ * @param {unknown} value
144
+ * @param {object} [options]
145
+ * @returns {boolean}
146
+ */
147
+ export function isPassword(value, options) {
148
+ return validatePassword(value, options).valid;
149
+ }
150
+
151
+ /**
152
+ * Alias for {@link isPassword}.
153
+ *
154
+ * @param {unknown} value
155
+ * @param {object} [options]
156
+ * @returns {boolean}
157
+ */
158
+ export function isStrongPassword(value, options) {
159
+ return isPassword(value, options);
160
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Validates an object of fields against a schema of validation rules.
3
+ *
4
+ * Each schema entry is an array of rules. A rule can be:
5
+ * - A function `(value, data) => boolean | { valid: boolean, errors?: string[] }`
6
+ * - An object `{ validator, message?, options? }` (or `{ rule, message?, options? }`)
7
+ *
8
+ * @param {Record<string, unknown>} data - Key-value object to validate.
9
+ * @param {Record<string, Array<Function | { validator?: Function, rule?: Function, message?: string, options?: object }>>} schema
10
+ * @returns {{ valid: boolean, errors: Record<string, string[]> }}
11
+ */
12
+ export function validate(data, schema) {
13
+ if (!data || typeof data !== 'object') {
14
+ return { valid: false, errors: { _root: ['Input data must be an object.'] } };
15
+ }
16
+ if (!schema || typeof schema !== 'object') {
17
+ return { valid: true, errors: {} };
18
+ }
19
+
20
+ const errors = {};
21
+
22
+ for (const [field, rules] of Object.entries(schema)) {
23
+ if (!Array.isArray(rules)) {
24
+ continue;
25
+ }
26
+ const value = data[field];
27
+ const fieldErrors = [];
28
+
29
+ for (const entry of rules) {
30
+ let fn;
31
+ let message;
32
+ let options;
33
+
34
+ if (typeof entry === 'function') {
35
+ fn = entry;
36
+ } else if (entry && typeof entry === 'object') {
37
+ fn = entry.validator || entry.rule;
38
+ message = entry.message;
39
+ options = entry.options;
40
+ }
41
+
42
+ if (typeof fn !== 'function') {
43
+ continue;
44
+ }
45
+
46
+ const result = options !== undefined ? fn(value, options) : fn(value, data);
47
+
48
+ if (typeof result === 'boolean') {
49
+ if (!result) {
50
+ fieldErrors.push(message || `Field "${field}" is invalid.`);
51
+ }
52
+ } else if (result && typeof result === 'object' && 'valid' in result) {
53
+ if (!result.valid) {
54
+ if (message) {
55
+ fieldErrors.push(message);
56
+ } else if (Array.isArray(result.errors) && result.errors.length > 0) {
57
+ fieldErrors.push(...result.errors);
58
+ } else {
59
+ fieldErrors.push(`Field "${field}" is invalid.`);
60
+ }
61
+ }
62
+ }
63
+ }
64
+
65
+ if (fieldErrors.length > 0) {
66
+ errors[field] = fieldErrors;
67
+ }
68
+ }
69
+
70
+ return {
71
+ valid: Object.keys(errors).length === 0,
72
+ errors,
73
+ };
74
+ }
@@ -0,0 +1,238 @@
1
+ export interface EmailValidationOptions {
2
+ /** Whether to trim leading/trailing whitespace before validating. Default: `false`. */
3
+ trim?: boolean;
4
+ /** Whitelist of allowed email domains (case-insensitive). */
5
+ allowedDomains?: string[];
6
+ /** Blacklist of blocked email domains (case-insensitive). */
7
+ blockedDomains?: string[];
8
+ }
9
+
10
+ export interface EmailValidationResult {
11
+ valid: boolean;
12
+ errors: string[];
13
+ }
14
+
15
+ export type PasswordStrength = 'weak' | 'medium' | 'strong';
16
+
17
+ export interface PasswordValidationOptions {
18
+ /** Minimum password length. Default: `8`. */
19
+ minLength?: number;
20
+ /** Maximum password length. Default: `128`. */
21
+ maxLength?: number;
22
+ /** Require at least one uppercase letter. Default: `true`. */
23
+ requireUppercase?: boolean;
24
+ /** Require at least one lowercase letter. Default: `true`. */
25
+ requireLowercase?: boolean;
26
+ /** Require at least one digit (0-9). Default: `true`. */
27
+ requireDigits?: boolean;
28
+ /** Alias for `requireDigits`. */
29
+ requireNumbers?: boolean;
30
+ /** Require at least one special character. Default: `true`. */
31
+ requireSpecialChars?: boolean;
32
+ /** Optional custom string of characters treated as special characters. */
33
+ specialChars?: string;
34
+ /** Whether whitespace characters are allowed. Default: `false`. */
35
+ allowSpaces?: boolean;
36
+ }
37
+
38
+ export interface PasswordChecks {
39
+ minLength: boolean;
40
+ maxLength: boolean;
41
+ uppercase: boolean;
42
+ lowercase: boolean;
43
+ digits: boolean;
44
+ specialChars: boolean;
45
+ noSpaces: boolean;
46
+ }
47
+
48
+ export interface PasswordValidationResult {
49
+ valid: boolean;
50
+ errors: string[];
51
+ strength: PasswordStrength;
52
+ checks: PasswordChecks;
53
+ }
54
+
55
+ export interface NumberValidationOptions {
56
+ /** Allow leading "-" sign. Default: `true`. */
57
+ allowNegative?: boolean;
58
+ /** Allow decimal point. Default: `true`. */
59
+ allowDecimal?: boolean;
60
+ /** Allow leading "+" sign. Default: `true`. */
61
+ allowPlus?: boolean;
62
+ }
63
+
64
+ export interface AlphabetValidationOptions {
65
+ /** Allow spaces between alphabetic characters. Default: `false`. */
66
+ allowSpaces?: boolean;
67
+ }
68
+
69
+ export interface AlphanumericValidationOptions {
70
+ /** Allow spaces. Default: `false`. */
71
+ allowSpaces?: boolean;
72
+ /** Allow underscores ("_"). Default: `false`. */
73
+ allowUnderscore?: boolean;
74
+ /** Allow hyphens ("-"). Default: `false`. */
75
+ allowHyphen?: boolean;
76
+ }
77
+
78
+ export interface EmptyValidationOptions {
79
+ /** Treat whitespace-only strings as empty. Default: `true`. */
80
+ ignoreWhitespace?: boolean;
81
+ }
82
+
83
+ export interface LengthValidationOptions {
84
+ min?: number;
85
+ max?: number;
86
+ }
87
+
88
+ export interface RangeValidationOptions {
89
+ min?: number;
90
+ max?: number;
91
+ }
92
+
93
+ export interface PhoneValidationOptions {
94
+ minDigits?: number;
95
+ maxDigits?: number;
96
+ allowFormatting?: boolean;
97
+ }
98
+
99
+ export interface URLValidationOptions {
100
+ requireProtocol?: boolean;
101
+ protocols?: string[];
102
+ allowLocalhost?: boolean;
103
+ }
104
+
105
+ export interface UsernameValidationOptions {
106
+ minLength?: number;
107
+ maxLength?: number;
108
+ allowUnderscore?: boolean;
109
+ allowHyphen?: boolean;
110
+ allowDot?: boolean;
111
+ mustStartWithLetter?: boolean;
112
+ }
113
+
114
+ export type UUIDVersion = 1 | 2 | 3 | 4 | 5 | 'all';
115
+
116
+ export type ValidatorFn = (
117
+ value: unknown,
118
+ contextOrOptions?: any
119
+ ) => boolean | { valid: boolean; errors?: string[] };
120
+
121
+ export interface SchemaRuleObject {
122
+ validator?: ValidatorFn;
123
+ rule?: ValidatorFn;
124
+ message?: string;
125
+ options?: Record<string, unknown>;
126
+ }
127
+
128
+ export type SchemaRule = ValidatorFn | SchemaRuleObject;
129
+
130
+ export type ValidationSchema = Record<string, SchemaRule[]>;
131
+
132
+ export interface SchemaValidationResult {
133
+ valid: boolean;
134
+ errors: Record<string, string[]>;
135
+ }
136
+
137
+ // Email
138
+ export declare function isEmail(value: unknown, options?: EmailValidationOptions): boolean;
139
+ export declare function validateEmail(
140
+ value: unknown,
141
+ options?: EmailValidationOptions
142
+ ): EmailValidationResult;
143
+
144
+ // Password
145
+ export declare function isPassword(value: unknown, options?: PasswordValidationOptions): boolean;
146
+ export declare function isStrongPassword(
147
+ value: unknown,
148
+ options?: PasswordValidationOptions
149
+ ): boolean;
150
+ export declare function validatePassword(
151
+ value: unknown,
152
+ options?: PasswordValidationOptions
153
+ ): PasswordValidationResult;
154
+ export declare function getPasswordStrength(value: unknown): PasswordStrength;
155
+
156
+ // Numbers & Digits
157
+ export declare function isNumber(value: unknown, options?: NumberValidationOptions): boolean;
158
+ export declare function isNumeric(value: unknown, options?: NumberValidationOptions): boolean;
159
+ export declare function hasNumbers(value: unknown): boolean;
160
+ export declare function isDigits(value: unknown): boolean;
161
+ export declare function hasDigits(value: unknown): boolean;
162
+
163
+ // Alphabets & Alphanumeric
164
+ export declare function isAlphabets(value: unknown, options?: AlphabetValidationOptions): boolean;
165
+ export declare function isAlpha(value: unknown, options?: AlphabetValidationOptions): boolean;
166
+ export declare function hasAlphabets(value: unknown): boolean;
167
+ export declare function hasAlpha(value: unknown): boolean;
168
+ export declare function isAlphanumeric(
169
+ value: unknown,
170
+ options?: AlphanumericValidationOptions
171
+ ): boolean;
172
+
173
+ // Special Characters & Case
174
+ export declare function isSpecialChars(value: unknown, customChars?: string): boolean;
175
+ export declare function hasSpecialChars(value: unknown, customChars?: string): boolean;
176
+ export declare function hasNoSpecialChars(value: unknown, customChars?: string): boolean;
177
+ export declare function hasUppercase(value: unknown): boolean;
178
+ export declare function hasLowercase(value: unknown): boolean;
179
+ export declare function isUppercase(value: unknown): boolean;
180
+ export declare function isLowercase(value: unknown): boolean;
181
+ export declare function hasSpaces(value: unknown): boolean;
182
+
183
+ // Common Validators
184
+ export declare function isEmpty(value: unknown, options?: EmptyValidationOptions): boolean;
185
+ export declare function isRequired(value: unknown, options?: EmptyValidationOptions): boolean;
186
+ export declare function isLength(value: unknown, options?: LengthValidationOptions): boolean;
187
+ export declare function isRange(value: unknown, options?: RangeValidationOptions): boolean;
188
+ export declare function isPhone(value: unknown, options?: PhoneValidationOptions): boolean;
189
+ export declare function isURL(value: unknown, options?: URLValidationOptions): boolean;
190
+ export declare function isUsername(value: unknown, options?: UsernameValidationOptions): boolean;
191
+ export declare function isUUID(value: unknown, version?: UUIDVersion): boolean;
192
+ export declare function matches(value: unknown, pattern: RegExp | string, flags?: string): boolean;
193
+
194
+ // Schema Validation
195
+ export declare function validate(
196
+ data: Record<string, unknown>,
197
+ schema: ValidationSchema
198
+ ): SchemaValidationResult;
199
+
200
+ export interface ValidationSuite {
201
+ isEmail: typeof isEmail;
202
+ validateEmail: typeof validateEmail;
203
+ isPassword: typeof isPassword;
204
+ isStrongPassword: typeof isStrongPassword;
205
+ validatePassword: typeof validatePassword;
206
+ getPasswordStrength: typeof getPasswordStrength;
207
+ isNumber: typeof isNumber;
208
+ isNumeric: typeof isNumeric;
209
+ hasNumbers: typeof hasNumbers;
210
+ isDigits: typeof isDigits;
211
+ hasDigits: typeof hasDigits;
212
+ isAlphabets: typeof isAlphabets;
213
+ isAlpha: typeof isAlpha;
214
+ hasAlphabets: typeof hasAlphabets;
215
+ hasAlpha: typeof hasAlpha;
216
+ isAlphanumeric: typeof isAlphanumeric;
217
+ isSpecialChars: typeof isSpecialChars;
218
+ hasSpecialChars: typeof hasSpecialChars;
219
+ hasNoSpecialChars: typeof hasNoSpecialChars;
220
+ hasUppercase: typeof hasUppercase;
221
+ hasLowercase: typeof hasLowercase;
222
+ isUppercase: typeof isUppercase;
223
+ isLowercase: typeof isLowercase;
224
+ hasSpaces: typeof hasSpaces;
225
+ isEmpty: typeof isEmpty;
226
+ isRequired: typeof isRequired;
227
+ isLength: typeof isLength;
228
+ isRange: typeof isRange;
229
+ isPhone: typeof isPhone;
230
+ isURL: typeof isURL;
231
+ isUsername: typeof isUsername;
232
+ isUUID: typeof isUUID;
233
+ matches: typeof matches;
234
+ validate: typeof validate;
235
+ }
236
+
237
+ export declare const validation: ValidationSuite;
238
+ export default validation;
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "phani-validations",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Lightweight, zero-dependency JavaScript/TypeScript validation library for emails, passwords, numbers, digits, alphabets, alphanumeric strings, special characters, and more.",
5
+ "author": "Phani",
6
+ "keywords": [
7
+ "validation",
8
+ "validator",
9
+ "email",
10
+ "password",
11
+ "alphanumeric",
12
+ "alphabets",
13
+ "digits",
14
+ "numbers",
15
+ "special-characters",
16
+ "form-validation"
17
+ ],
18
+ "license": "MIT",
19
+ "type": "module",
20
+ "main": "./dist/cjs/index.js",
21
+ "module": "./dist/esm/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/esm/index.js",
27
+ "require": "./dist/cjs/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "scripts": {
36
+ "build": "node scripts/build.mjs",
37
+ "test": "npm run build && node --test test/*.test.js test/*.test.cjs",
38
+ "prepublishOnly": "npm test"
39
+ },
40
+ "engines": {
41
+ "node": ">=16.0.0"
42
+ }
43
+ }