Defining Data Validation Guidelines for JavaScript Functions

Establish rules for data validation within functions to prevent runtime errors and ensure data integrity.

0 likes
37 views

Rule Content

# Defining Data Validation Guidelines for JavaScript Functions

## Description

Establish rules for data validation within functions to prevent runtime errors and ensure data integrity.

## Category

JavaScript Cursor Rules

## Rules

### 1. Input Validation

- **Type Checking**:
  - Use `typeof` and `instanceof` to verify input types.
  - For complex structures, utilize schema validation libraries like [Zod](https://zod.dev/) or [Joi](https://joi.dev/).

- **Required Fields**:
  - Ensure all mandatory parameters are present.
  - Provide default values for optional parameters when appropriate.

- **Range and Format Validation**:
  - Validate numerical inputs against acceptable ranges.
  - Use regular expressions to validate string formats (e.g., email addresses, phone numbers).

### 2. Output Validation

- **Consistent Return Types**:
  - Ensure functions return values of the expected type.
  - Document return types clearly in function comments.

- **Data Sanitization**:
  - Sanitize output data to prevent security vulnerabilities like XSS.
  - Use libraries such as [DOMPurify](https://github.com/cure53/DOMPurify) for HTML sanitization.

### 3. Error Handling

- **Graceful Degradation**:
  - Implement try-catch blocks to handle exceptions.
  - Provide meaningful error messages to aid debugging.

- **Custom Error Types**:
  - Define custom error classes for specific error scenarios.
  - Include relevant information in error objects to facilitate troubleshooting.

### 4. Documentation

- **Function Annotations**:
  - Use JSDoc comments to describe function parameters, return types, and exceptions.
  - Include examples of valid and invalid inputs.

- **Validation Logic Documentation**:
  - Clearly document the validation rules applied within functions.
  - Explain the rationale behind specific validation checks.

### 5. Testing

- **Unit Tests**:
  - Write tests to cover various input scenarios, including edge cases.
  - Use testing frameworks like [Jest](https://jestjs.io/) or [Mocha](https://mochajs.org/).

- **Mocking and Stubbing**:
  - Utilize mocking libraries to simulate different input conditions.
  - Ensure tests are isolated and do not depend on external systems.

### 6. Performance Considerations

- **Efficient Validation**:
  - Optimize validation logic to minimize performance overhead.
  - Avoid redundant checks by validating data at the earliest point possible.

- **Asynchronous Validation**:
  - For operations involving I/O, perform validation asynchronously.
  - Use async/await syntax to handle asynchronous validation cleanly.

### 7. Security Best Practices

- **Injection Prevention**:
  - Escape or sanitize inputs to prevent injection attacks.
  - Use parameterized queries when interacting with databases.

- **Dependency Management**:
  - Keep validation libraries up to date to mitigate known vulnerabilities.
  - Regularly audit dependencies for security issues.

### 8. Consistency and Reusability

- **Centralized Validation Functions**:
  - Create reusable validation functions or modules.
  - Ensure consistent validation logic across the codebase.

- **Configuration-Driven Validation**:
  - Use configuration files to define validation rules, allowing for easy updates and maintenance.
  - Separate validation logic from business logic to enhance maintainability.

## Implementation Example

const Joi = require('joi');

/**
 * Validates user input for creating a new account.
 * @param {Object} userInput - The user input data.
 * @returns {Object} - The validation result.
 */
function validateUserInput(userInput) {
  const schema = Joi.object({
    username: Joi.string().alphanum().min(3).max(30).required(),
    email: Joi.string().email().required(),
    password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(),
    birthdate: Joi.date().less('now').required(),
  });

  return schema.validate(userInput);
}

// Example usage
const userInput = {
  username: 'JohnDoe',
  email: 'john.doe@example.com',
  password: 'password123',
  birthdate: '1990-01-01',
};

const { error } = validateUserInput(userInput);
if (error) {
  console.error('Validation error:', error.details);
} else {
  console.log('Validation successful');
}
By adhering to these guidelines, JavaScript functions will be more robust, secure, and maintainable, leading to improved overall code quality.