JSPM

@bernierllc/csv-validator

0.1.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 29
  • Score
    100M100P100Q66738F
  • License ISC

Atomic CSV validation utilities with comprehensive data type checking and custom validation rules

Package Exports

  • @bernierllc/csv-validator
  • @bernierllc/csv-validator/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@bernierllc/csv-validator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@bernierllc/csv-validator

Atomic CSV validation utilities with comprehensive data type checking and custom validation rules.

Features

  • Built-in Validators: Email, phone, URL, number, integer, date, boolean, string, and select validators
  • Custom Validation: Support for custom validation functions and business rules
  • Schema-based Validation: Define validation schemas with field types and rules
  • Error Reporting: Detailed error messages with suggestions for fixes
  • Bulk Operations: Fix multiple errors at once with bulk fix suggestions
  • Statistics: Get validation statistics and error breakdowns
  • Type Safety: Full TypeScript support with strict typing

Installation

npm install @bernierllc/csv-validator

Quick Start

import { validateData, ValidationSchema } from '@bernierllc/csv-validator';

// Define a validation schema
const schema: ValidationSchema = {
  id: 'user-import',
  name: 'User Import Schema',
  fields: [
    {
      key: 'name',
      label: 'Full Name',
      type: 'string',
      required: true,
      validation: { min: 2, max: 100 }
    },
    {
      key: 'email',
      label: 'Email Address',
      type: 'email',
      required: true
    },
    {
      key: 'age',
      label: 'Age',
      type: 'integer',
      required: false,
      validation: { min: 0, max: 120 }
    }
  ]
};

// Validate your data
const data = [
  { name: 'John Doe', email: 'john@example.com', age: '30' },
  { name: 'Jane Smith', email: 'invalid-email', age: '150' },
  { name: '', email: 'jane@example.com', age: '25' }
];

const validatedRows = validateData(data, schema);

// Check results
validatedRows.forEach(row => {
  if (row.isValid) {
    console.log(`Row ${row.rowIndex}: Valid`);
  } else {
    console.log(`Row ${row.rowIndex}: Invalid`);
    row.errors.forEach(error => {
      console.log(`  - ${error.field}: ${error.error}`);
    });
  }
});

API Reference

Core Functions

validateData(rows, schema, customValidators?, businessRules?)

Validates data against a schema and returns validated rows with errors.

const validatedRows = validateData(
  data,
  schema,
  customValidators,
  businessRules
);

validateField(value, type, validation?, rowData?)

Validates a single field value against its type and validation rules.

const result = validateField('test@example.com', 'email');
if (!result.isValid) {
  console.log(result.error);
  console.log(result.suggestion);
}

validateRequired(value)

Validates that a required field has a value.

const result = validateRequired('');
if (!result.isValid) {
  console.log(result.error); // "This field is required"
}

Built-in Validators

The package includes validators for common data types:

Email Validator

import { validators } from '@bernierllc/csv-validator';

const result = validators.email('test@example.com');
// Returns: { isValid: true }

const invalid = validators.email('invalid-email');
// Returns: { isValid: false, error: 'Invalid email format', suggestion: 'invalid-email@example.com' }

Phone Validator

const result = validators.phone('1234567890');
// Returns: { isValid: true, suggestion: '(123) 456-7890' }

Number Validator

const result = validators.number('123.45', { min: 0, max: 1000 });
// Returns: { isValid: true }

Date Validator

const result = validators.date('2023-01-01', { dateFormat: 'YYYY-MM-DD' });
// Returns: { isValid: true }

String Validator

const result = validators.string('test', { min: 3, max: 10, pattern: '^[a-z]+$' });
// Returns: { isValid: true }

Select Validator

const result = validators.select('red', { enum: ['red', 'green', 'blue'] });
// Returns: { isValid: true }

Custom Validators

Create custom validation functions for complex business logic:

import { CustomValidator } from '@bernierllc/csv-validator';

const customValidators: CustomValidator[] = [
  {
    name: 'adult-check',
    fields: ['age'],
    validate: (data) => ({
      isValid: data.age >= 18,
      error: 'Must be 18 or older'
    })
  },
  {
    name: 'email-domain-check',
    fields: ['email'],
    validate: (data) => ({
      isValid: data.email.endsWith('@company.com'),
      error: 'Must use company email domain'
    })
  }
];

Business Rules

Define cross-field validation rules:

import { BusinessRule } from '@bernierllc/csv-validator';

const businessRules: BusinessRule[] = [
  {
    name: 'date-range',
    description: 'End date must be after start date',
    fields: ['startDate', 'endDate'],
    validate: (data) => {
      const start = new Date(data.startDate);
      const end = new Date(data.endDate);
      return {
        isValid: end > start,
        error: 'End date must be after start date'
      };
    },
    priority: 1
  }
];

Error Handling

Fix Individual Errors

import { fixValidationError } from '@bernierllc/csv-validator';

const fixedRow = fixValidationError(row, 'email', 'valid@example.com', schema);

Bulk Fixes

import { suggestBulkFixes, applyBulkFix } from '@bernierllc/csv-validator';

// Get suggestions for bulk fixes
const suggestions = suggestBulkFixes(validatedRows);

// Apply a bulk fix
const fixedRows = applyBulkFix(
  validatedRows,
  'email',
  'default@example.com',
  [1, 2, 3],
  schema
);

Error Statistics

import { getValidationStats, groupErrorsByField, groupErrorsByType } from '@bernierllc/csv-validator';

// Get overall statistics
const stats = getValidationStats(validatedRows);
console.log(`Valid: ${stats.valid}/${stats.total}`);
console.log(`Common errors:`, stats.commonErrors);

// Group errors by field
const fieldErrors = groupErrorsByField(validatedRows);

// Group errors by type
const typeErrors = groupErrorsByType(validatedRows);

Schema Definition

Define validation schemas with field types and rules:

import { ValidationSchema } from '@bernierllc/csv-validator';

const schema: ValidationSchema = {
  id: 'product-import',
  name: 'Product Import Schema',
  description: 'Schema for importing product data',
  version: '1.0.0',
  fields: [
    {
      key: 'name',
      label: 'Product Name',
      type: 'string',
      required: true,
      validation: { min: 1, max: 200 }
    },
    {
      key: 'price',
      label: 'Price',
      type: 'number',
      required: true,
      validation: { min: 0 }
    },
    {
      key: 'category',
      label: 'Category',
      type: 'select',
      required: true,
      validation: { enum: ['electronics', 'clothing', 'books'] }
    },
    {
      key: 'description',
      label: 'Description',
      type: 'string',
      required: false,
      validation: { max: 1000 }
    }
  ],
  globalValidation: {
    customValidators: [
      {
        name: 'price-format',
        fields: ['price'],
        validate: (data) => ({
          isValid: Number.isInteger(data.price * 100),
          error: 'Price must have at most 2 decimal places'
        })
      }
    ],
    businessRules: [
      {
        name: 'name-unique',
        description: 'Product names must be unique',
        fields: ['name'],
        validate: (data) => {
          // Implementation would check against existing products
          return { isValid: true };
        }
      }
    ]
  }
};

Examples

See the examples/ directory for complete usage examples:

  • Basic validation
  • Custom validators
  • Business rules
  • Error handling
  • Bulk operations

Testing

Run the test suite:

npm test
npm run test:coverage

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

License

Copyright (c) 2025 Bernier LLC

This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.