{"_id":"@alok5953/isovalid","_rev":"2-5c64455e935e7e9a49aed6be7d90e989","name":"@alok5953/isovalid","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@alok5953/isovalid","version":"1.0.0","keywords":["validation","schema","typescript","isomorphic","form-validation"],"author":"","license":"MIT","_id":"@alok5953/isovalid@1.0.0","maintainers":[{"name":"alok5953","email":"alokkaushik93@gmail.com"}],"dist":{"shasum":"a942f97614d2bdb4209dd1a1ad5b11364dd946d5","tarball":"https://registry.npmjs.org/@alok5953/isovalid/-/isovalid-1.0.0.tgz","fileCount":14,"integrity":"sha512-4YFaWEbZY+4HrY2ufHsW/YAexN3OpIxIhaKD73pwl5uZ5tD8NQLgh/WMmgPoTG4NjWuiQXNeq2225l8qXV4aUQ==","signatures":[{"sig":"MEUCIQDekrNu974wlHx1QKkvuO8ujXfmvQiFmLIME7tUEoEgigIgUpAKpvSXkBT5MWAnA5wz1bAbESx3DRQXS8NKJHbt6Xs=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":20240},"main":"dist/index.js","types":"dist/index.d.ts","scripts":{"test":"jest","build":"tsc","prepublish":"npm run build","test:watch":"jest --watch"},"_npmUser":{"name":"alok5953","email":"alokkaushik93@gmail.com"},"_npmVersion":"10.9.2","description":"Isomorphic data validation library for TypeScript/JavaScript","directories":{},"_nodeVersion":"22.14.0","_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","ts-jest":"^29.2.6","typescript":"^5.8.2","@types/jest":"^29.5.14","@types/node":"^22.13.9"},"_npmOperationalInternal":{"tmp":"tmp/isovalid_1.0.0_1741276734452_0.023623098120757247","host":"s3://npm-registry-packages-npm-production"},"deprecated":"This package has been renamed to 'isovalid'. Please install 'isovalid' instead."}},"time":{"created":"2025-03-06T15:58:54.371Z","modified":"2025-03-10T13:54:01.238Z","1.0.0":"2025-03-06T15:58:54.614Z"},"license":"MIT","keywords":["validation","schema","typescript","isomorphic","form-validation"],"description":"Isomorphic data validation library for TypeScript/JavaScript","maintainers":[{"name":"alok5953","email":"alokkaushik93@gmail.com"}],"readme":"# IsoValid\n\nA lightweight, isomorphic data validation library for TypeScript and JavaScript that works seamlessly in both browser and Node.js environments. IsoValid is designed to provide a unified validation experience across your entire application stack.\n\n## Why IsoValid?\n\nIn modern web applications, data validation is crucial at multiple layers:\n- Client-side form validation for immediate user feedback\n- API request/response validation for data integrity\n- Server-side validation for security\n\nTraditionally, developers had to:\n1. Write separate validation logic for frontend and backend\n2. Maintain multiple validation libraries\n3. Deal with inconsistencies between environments\n\nIsoValid solves these problems by providing:\n- 🌐 **True Isomorphic Support** - The exact same validation code runs in both browser and Node.js\n- 🎯 **TypeScript-First Design** - Built from the ground up with TypeScript for excellent type inference\n- 🪶 **Minimal Bundle Size** - Core validation features without unnecessary bloat\n- 🔄 **Developer-Friendly API** - Intuitive, chainable interface for building schemas\n- ⚡ **High Performance** - Optimized validation with minimal overhead\n- 🎨 **Extensible Design** - Easy to add custom validators and error messages\n\n## Installation\n\n```bash\nnpm install isovalid\n```\n\n## Architecture\n\nIsoValid is built on a flexible, extensible architecture:\n\n### Core Components\n\n1. **Base Schema Class**\n   - Abstract foundation for all schema types\n   - Handles common validation logic\n   - Manages optional/nullable states\n\n2. **Type-Specific Schemas**\n   - StringSchema: String validation with length, pattern, format checks\n   - NumberSchema: Numeric validation with range, integer, sign checks\n   - More types coming soon (Boolean, Array, Object)\n\n3. **Validation Pipeline**\n   - Multi-stage validation process\n   - Custom validator support\n   - Detailed error reporting\n\n## API Reference\n\n### String Validation\n\n```typescript\nconst stringSchema = v.string()\n  .min(2)           // Minimum length\n  .max(50)          // Maximum length\n  .email()          // Email format\n  .matches(/regex/) // Custom regex pattern\n  .trimmed()        // Auto-trim whitespace\n  .setOptional()    // Allow undefined\n  .setNullable()    // Allow null\n  .custom(value => value.includes('@') ? null : 'Must include @'); // Custom validation\n```\n\n### Number Validation\n\n```typescript\nconst numberSchema = v.number()\n  .min(0)         // Minimum value\n  .max(100)       // Maximum value\n  .integer()      // Must be an integer\n  .positive()     // Must be > 0\n  .setOptional()  // Allow undefined\n  .setNullable(); // Allow null\n```\n\n### Validation Results\n\nAll validations return a structured result:\n\n```typescript\ninterface ValidationResult {\n  valid: boolean;\n  errors: Array<{\n    path: string[];\n    message: string;\n  }>;\n}\n```\n\n## Real-World Examples\n\n### 1. React Form Validation\n\n```typescript\nimport { v } from 'isovalid';\nimport { useState, FormEvent } from 'react';\n\nconst userSchema = {\n  username: v.string().min(3).max(20),\n  email: v.string().email(),\n  age: v.number().integer().min(18)\n};\n\nfunction RegistrationForm() {\n  const [formData, setFormData] = useState({\n    username: '',\n    email: '',\n    age: ''\n  });\n  const [errors, setErrors] = useState<Record<string, string>>({});\n\n  const validateField = (field: keyof typeof userSchema, value: any) => {\n    const result = userSchema[field].validate(value);\n    return result.valid ? null : result.errors[0].message;\n  };\n\n  const handleSubmit = (e: FormEvent) => {\n    e.preventDefault();\n    const newErrors: Record<string, string> = {};\n    \n    // Validate all fields\n    Object.entries(formData).forEach(([field, value]) => {\n      const error = validateField(field as keyof typeof userSchema, value);\n      if (error) newErrors[field] = error;\n    });\n\n    if (Object.keys(newErrors).length === 0) {\n      // Form is valid, submit data\n      console.log('Submitting:', formData);\n    } else {\n      setErrors(newErrors);\n    }\n  };\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <div>\n        <input\n          type=\"text\"\n          value={formData.username}\n          onChange={e => setFormData(prev => ({ ...prev, username: e.target.value }))}\n          placeholder=\"Username\"\n        />\n        {errors.username && <span className=\"error\">{errors.username}</span>}\n      </div>\n      {/* Similar fields for email and age */}\n      <button type=\"submit\">Register</button>\n    </form>\n  );\n}\n```\n\n### 2. Express API Validation\n\n```typescript\nimport express from 'express';\nimport { v } from 'isovalid';\n\nconst app = express();\napp.use(express.json());\n\nconst productSchema = {\n  name: v.string().min(3).max(100),\n  price: v.number().min(0),\n  category: v.string().custom(value =>\n    ['electronics', 'books', 'clothing'].includes(value)\n      ? null\n      : 'Invalid category'\n  )\n};\n\napp.post('/api/products', (req, res) => {\n  const errors = Object.entries(productSchema)\n    .map(([field, schema]) => ({\n      field,\n      result: schema.validate(req.body[field])\n    }))\n    .filter(({ result }) => !result.valid)\n    .map(({ field, result }) => ({\n      field,\n      message: result.errors[0].message\n    }));\n\n  if (errors.length > 0) {\n    return res.status(400).json({ errors });\n  }\n\n  // Process valid product data\n  const product = req.body;\n  // Save to database, etc.\n  res.status(201).json(product);\n});\n```\n\n## Best Practices\n\n1. **Schema Reuse**\n   - Define schemas once and share between frontend and backend\n   - Keep schemas in a shared directory accessible to both environments\n\n2. **Type Safety**\n   - Leverage TypeScript's type inference with IsoValid\n   - Define interfaces that match your schemas\n\n3. **Performance**\n   - Create schemas outside request handlers\n   - Reuse schema instances when possible\n\n4. **Error Handling**\n   - Always check the `valid` property before accessing data\n   - Provide user-friendly error messages in custom validators\n\n## Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n1. Fork the repository\n2. Create your feature branch\n3. Write tests for your changes\n4. Submit a pull request\n\n## Testing\n\nIsoValid uses Jest for testing. Run the test suite:\n\n```bash\nnpm test\n```\n\nCurrent test coverage: >88%\n\n## Roadmap\n\n- [ ] Array schema type\n- [ ] Object schema type with nested validation\n- [ ] Custom error message templates\n- [ ] Async validation support\n- [ ] Integration with popular form libraries\n- [ ] Schema composition and inheritance\n\n## License\n\nMIT © [IsoValid](LICENSE)\n\n## Support\n\n- GitHub Issues: Report bugs and feature requests\n- Documentation: Check our [Wiki](https://github.com/isovalid/isovalid/wiki)\n- Stack Overflow: Tag your questions with `isovalid`\n","readmeFilename":"README.md"}