npm package: @aleezahussain/form-validation-sdk
Description: A simple and lightweight form validation SDK for JavaScript and TypeScript applications
Author: Aleeza Hussain
Latest version: 1.0.0

# Form Validation SDK

A simple and lightweight form validation SDK for JavaScript and TypeScript applications.

[![npm version](https://badge.fury.io/js/@aleezahussain%2Fform-validation-sdk.svg)](https://badge.fury.io/js/@aleezahussain%2Fform-validation-sdk)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)

## 📦 Installation

```bash
npm install @aleezahussain/form-validation-sdk
```

## 🚀 Quick Start

### JavaScript

```javascript
const { FormSDK } = require('@aleezahussain/form-validation-sdk');

// Create form data
const formData = {
  name: 'John Doe',
  email: 'john@example.com',
  phone: '123-456-7890'
};

// Create SDK instance
const sdk = new FormSDK(formData);

// Validate the form
const result = sdk.validate();

if (Array.isArray(result)) {
  console.log('Validation errors:', result);
  // Output: ["name is required", "email is required"]
} else {
  console.log('Success:', result);
  // Output: "Form is valid!"
}
```

### TypeScript

```typescript
import { FormSDK, Fields, ValidationResult } from '@aleezahussain/form-validation-sdk';

// Define your form data with types
const formData: Fields = {
  name: 'John Doe',
  email: 'john@example.com',
  phone: ''  // This will trigger validation error
};

// Create SDK instance
const sdk = new FormSDK(formData);

// Validate with typed result
const result: ValidationResult = sdk.validate();

if (Array.isArray(result)) {
  console.log('Validation errors:', result);
  // Output: ["phone is required"]
} else {
  console.log('Success:', result);
}
```

## 📚 API Reference

### `FormSDK`

The main class for form validation.

#### Constructor

```typescript
new FormSDK(fields: Fields)
```

- `fields`: Object containing form field data where keys are field names and values are strings or undefined.

#### Methods

##### `validate(): ValidationResult`

Validates all form fields and returns either an array of error messages or a success message.

**Returns:**
- `string[]`: Array of error messages if validation fails
- `string`: Success message if all fields are valid

**Example:**
```typescript
const result = sdk.validate();
// Returns: ["name is required"] or "Form is valid!"
```

##### `getFields(): Fields`

Returns a copy of the current form field data.

**Example:**
```typescript
const currentFields = sdk.getFields();
console.log(currentFields); // { name: 'John', email: 'john@example.com' }
```

##### `updateFields(newFields: Partial<Fields>): void`

Updates form fields with new data.

**Example:**
```typescript
sdk.updateFields({ name: 'Jane Doe', age: '25' });
```

##### `isFieldValid(fieldName: string): boolean`

Checks if a specific field is valid (not empty).

**Example:**
```typescript
const isNameValid = sdk.isFieldValid('name');
console.log(isNameValid); // true or false
```

### Types

#### `Fields`

```typescript
interface Fields {
  [key: string]: string | undefined;
}
```

#### `ValidationResult`

```typescript
type ValidationResult = string[] | string;
```

## 🌟 Examples

### Basic Web Form

```html
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation Example</title>
</head>
<body>
    <form id="myForm">
        <input type="text" name="name" placeholder="Name" />
        <input type="email" name="email" placeholder="Email" />
        <input type="tel" name="phone" placeholder="Phone" />
        <button type="submit">Submit</button>
    </form>

    <script src="https://unpkg.com/@aleezahussain/form-validation-sdk/dist/index.js"></script>
    <script>
        document.getElementById('myForm').addEventListener('submit', (e) => {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const fields = Object.fromEntries(formData.entries());
            
            const sdk = new FormSDK(fields);
            const result = sdk.validate();
            
            if (Array.isArray(result)) {
                alert('Errors: ' + result.join(', '));
            } else {
                alert('Success: ' + result);
            }
        });
    </script>
</body>
</html>
```

### Express.js Server

```javascript
const express = require('express');
const { FormSDK } = require('@aleezahussain/form-validation-sdk');

const app = express();
app.use(express.json());

app.post('/submit-form', (req, res) => {
    const formSDK = new FormSDK(req.body);
    const result = formSDK.validate();
    
    if (Array.isArray(result)) {
        return res.status(400).json({ errors: result });
    }
    
    res.json({ message: result });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
```

### React Component

```tsx
import React, { useState } from 'react';
import { FormSDK, Fields } from '@aleezahussain/form-validation-sdk';

const MyForm: React.FC = () => {
  const [fields, setFields] = useState<Fields>({
    name: '',
    email: '',
    phone: ''
  });
  const [errors, setErrors] = useState<string[]>([]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const sdk = new FormSDK(fields);
    const result = sdk.validate();
    
    if (Array.isArray(result)) {
      setErrors(result);
    } else {
      setErrors([]);
      alert('Form submitted successfully!');
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFields({
      ...fields,
      [e.target.name]: e.target.value
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="name"
        value={fields.name || ''}
        onChange={handleChange}
        placeholder="Name"
      />
      <input
        name="email"
        value={fields.email || ''}
        onChange={handleChange}
        placeholder="Email"
      />
      <input
        name="phone"
        value={fields.phone || ''}
        onChange={handleChange}
        placeholder="Phone"
      />
      
      {errors.length > 0 && (
        <div>
          {errors.map((error, index) => (
            <p key={index} style={{ color: 'red' }}>{error}</p>
          ))}
        </div>
      )}
      
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;
```

## 🔧 Development

### Building from Source

```bash
# Clone the repository
git clone https://github.com/Bitsframe/form-sdk.git
cd form-sdk

# Install dependencies
npm install

# Build the package
npm run build

# Run in development mode
npm run dev
```

### Testing

```bash
npm test
```

## 📝 License

MIT © [Aleeza Hussain](https://github.com/Bitsframe)

## 🤝 Contributing

Contributions, issues, and feature requests are welcome!

1. Fork the project
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## 📞 Support

If you have any questions or need help, please [open an issue](https://github.com/Bitsframe/form-sdk/issues) on GitHub.

---

**Happy coding! 🚀**