npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@avalon-cloud/enhanced-validator

v1.1.0

Published

TypeScript 的驗證器套件,用來作為後端 API 的 Request 資料驗證

Downloads

151

Readme

Enhanced Validator

Enhanced Validator 是一個�大的 TypeScript 驗證庫,專為複雜的資料驗證需求設計。它提供了豐富的驗證功能、類型安全、鏈式 API 以及完整的錯誤處理機制。

特色

  • 🔒 完整的 TypeScript 支援與類型安全
  • 🌲 支援巢狀物件驗證(使用點記法)
  • 🔄 內建資料轉換功能
  • ⚡ 靈活的驗證模式(快速失敗或完整驗證)
  • 🎯 豐富的內建驗證規則
  • 🛠 支援自訂驗證規則
  • 📝 詳細的錯誤報告

安裝

npm install enhanced-validator
# 或
yarn add enhanced-validator

基本使用

簡單範例

import { EnhancedValidator } from 'enhanced-validator';

// 定義資料結構
interface UserData {
  username: string;
  email: string;
  age: number;
}

// 創建驗證器實例
const validator = new EnhancedValidator<UserData>();

// 設定驗證規則
validator
  .field('username')
    .isRequired('使用者名稱為必填')
    .isString()
    .minLength(3, '使用者名稱至少需要 3 個字元')
  .field('email')
    .isRequired('電子郵件為必填')
    .isEmail('���輸入有效的電子郵件地址')
  .field('age')
    .isNumber()
    .min(18, '年齡必須大於或等於 18 歲');

// 驗證資料
const data = {
  username: 'john',
  email: '[email protected]',
  age: 25
};

const result = await validator.validate(data);

巢狀物件驗證

interface ComplexData {
  user: {
    profile: {
      name: string;
      contact: {
        email: string;
      }
    }
  }
}

const validator = new EnhancedValidator<ComplexData>();

validator
  .field('user.profile.name')
    .isRequired()
  .field('user.profile.contact.email')
    .isEmail();

驗證規則

基本驗證

  • isRequired() - 檢查必填欄位
  • isString() - 檢查字串類型
  • isNumber() - 檢查數字類型
  • isBoolean() - 檢查布林類型
  • notEmpty() - 檢查非空字串

字串驗證

  • minLength(length: number) - 最小長度
  • maxLength(length: number) - 最大長度
  • isEmail() - 電子郵件格式
  • isBase64() - Base64 格式
  • isJSON() - JSON 字串格式

數字驗證

  • min(value: number) - 最小值
  • max(value: number) - 最大值

特殊格式驗證

  • isCreditCard() - 信用卡號碼
  • isIP(version?: 4 | 6) - IP 地址
  • isISBN(version?: 10 | 13) - ISBN 編號
  • isUUID(version?: 3 | 4 | 5) - UUID
  • isHexColor() - 十六進位色碼
  • isMACAddress() - MAC 地址

進階功能

驗證模式

// 快速失敗模式 - 遇到第一個錯誤就停止
validator.setValidationMode(ValidationMode.FAIL_FAST);

// 完整驗證模式 - 檢查所有欄位
validator.setValidationMode(ValidationMode.ALL);

資料轉換

validator
  .field('age')
    .transform(value => parseInt(value as string))
    .min(18);

自訂驗證

validator
  .field('password')
    .custom(
      value => {
        const pwd = value as string;
        return pwd.length >= 8 && /[A-Z]/.test(pwd);
      },
      '密碼必須至少 8 個字元且包含大寫字母'
    );

驗證結果

驗證結果包含以下資訊:

interface ValidationResult<T> {
  success: boolean;        // 驗證是否成功
  data?: T;               // 驗證後的資料(可能包含轉換後的值)
  errors: ValidationError[]; // 錯誤列表
  fieldErrors: {          // 依欄位分類的錯誤
    [K in keyof T]?: ValidationError[];
  };
}

錯誤處理範例

const result = await validator.validate(data);
if (!result.success) {
  // 取得所有錯誤
  console.log('驗證錯誤:', result.errors);
  
  // 取得特定欄位的錯誤
  if (result.fieldErrors.email) {
    console.log('電子郵件錯誤:', result.fieldErrors.email);
  }
}

最佳實踐

  1. 使用 TypeScript 介面定義資料結構
  2. 為每個驗證規則提供明確的錯誤訊息
  3. 根據需求選擇適當的驗證模式
  4. 善用資料轉換功能處理輸入資料
  5. 使用自訂驗證處理複雜的驗證邏輯
  6. 妥善處理驗證錯誤,提供良好的使用者體驗

授權

MIT License

貢獻

歡迎提交 Issue 和 Pull Request!