如何写表单数据构造脚本

wen 实用脚本 22

本文目录导读:

如何写表单数据构造脚本

  1. 基础表单数据构造(JavaScript)
  2. 动态表单数据构造(支持嵌套)
  3. 测试用表单数据生成器
  4. 使用建议

我来帮你写一个表单数据构造脚本,这里提供几个不同场景下的实现方案:

基础表单数据构造(JavaScript)

// 构造表单数据的工具函数
class FormDataBuilder {
  constructor() {
    this.formData = {};
    this.rules = {};
  }
  // 添加字段
  addField(name, value, options = {}) {
    this.formData[name] = value;
    if (options.required || options.type) {
      this.rules[name] = options;
    }
    return this;
  }
  // 批量添加字段
  addFields(fields) {
    Object.entries(fields).forEach(([key, value]) => {
      if (typeof value === 'object' && value.value !== undefined) {
        this.addField(key, value.value, value.options || {});
      } else {
        this.addField(key, value);
      }
    });
    return this;
  }
  // 构造最终数据
  build() {
    return {
      data: { ...this.formData },
      rules: { ...this.rules },
      toFormData: () => this.toFormData(),
      toJSON: () => JSON.stringify(this.formData),
      validate: () => this.validate()
    };
  }
  // 转换为 FormData 对象(用于文件上传等)
  toFormData() {
    const fd = new FormData();
    Object.entries(this.formData).forEach(([key, value]) => {
      if (value instanceof File || value instanceof Blob) {
        fd.append(key, value, value.name);
      } else if (Array.isArray(value)) {
        value.forEach((item, index) => {
          fd.append(`${key}[${index}]`, item);
        });
      } else {
        fd.append(key, value);
      }
    });
    return fd;
  }
  // 简单的数据验证
  validate() {
    const errors = [];
    Object.entries(this.rules).forEach(([field, rule]) => {
      const value = this.formData[field];
      if (rule.required && !value) {
        errors.push(`${field} 是必填字段`);
      }
      if (rule.type === 'email' && value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        errors.push(`${field} 格式不正确`);
      }
      if (rule.type === 'phone' && value && !/^1[3-9]\d{9}$/.test(value)) {
        errors.push(`${field} 手机号格式不正确`);
      }
      if (rule.maxLength && value && value.length > rule.maxLength) {
        errors.push(`${field} 长度不能超过 ${rule.maxLength}`);
      }
      if (rule.minLength && value && value.length < rule.minLength) {
        errors.push(`${field} 长度不能少于 ${rule.minLength}`);
      }
    });
    return {
      isValid: errors.length === 0,
      errors
    };
  }
}
// 使用示例
const builder = new FormDataBuilder();
// 添加表单字段
builder
  .addField('username', '张三', { required: true, minLength: 2, maxLength: 20 })
  .addField('email', 'zhangsan@example.com', { required: true, type: 'email' })
  .addField('phone', '13800138000', { type: 'phone' })
  .addFields({
    age: 25,
    gender: { value: 'male', options: { required: true } },
    avatar: new File([''], 'avatar.jpg', { type: 'image/jpeg' })
  });
// 构建数据
const formData = builder.build();
// 获取不同类型的数据
console.log('JSON 数据:', formData.toJSON());
console.log('验证结果:', formData.validate());
// 发送请求
fetch('/api/submit', {
  method: 'POST',
  body: formData.toFormData() // 支持文件上传
});

动态表单数据构造(支持嵌套)

class AdvancedFormBuilder {
  constructor(schema) {
    this.schema = schema || {};
    this.data = {};
    this._initData();
  }
  _initData() {
    // 根据 schema 初始化默认值
    Object.entries(this.schema).forEach(([key, config]) => {
      this.data[key] = config.default || '';
    });
  }
  // 设置字段值
  set(field, value) {
    if (field.includes('.')) {
      // 支持嵌套路径
      const keys = field.split('.');
      let current = this.data;
      keys.forEach((key, index) => {
        if (index === keys.length - 1) {
          current[key] = value;
        } else {
          if (!current[key]) current[key] = {};
          current = current[key];
        }
      });
    } else {
      this.data[field] = value;
    }
    return this;
  }
  // 设置数组字段
  setArray(field, items) {
    this.data[field] = items;
    return this;
  }
  // 添加数组项
  addArrayItem(field, item) {
    if (!this.data[field]) {
      this.data[field] = [];
    }
    this.data[field].push(item);
    return this;
  }
  // 生成表单数据
  generate() {
    return {
      data: this.data,
      schema: this.schema,
      toUrlEncoded: () => this._toUrlEncoded(),
      toFormData: () => this._toFormData(),
      toXML: () => this._toXML()
    };
  }
  _toUrlEncoded() {
    const params = new URLSearchParams();
    this._flattenObject(this.data, '', params);
    return params.toString();
  }
  _flattenObject(obj, prefix, params) {
    Object.entries(obj).forEach(([key, value]) => {
      const fullKey = prefix ? `${prefix}[${key}]` : key;
      if (value && typeof value === 'object' && !Array.isArray(value)) {
        this._flattenObject(value, fullKey, params);
      } else if (Array.isArray(value)) {
        value.forEach((item, index) => {
          params.append(`${fullKey}[${index}]`, item);
        });
      } else {
        params.append(fullKey, value);
      }
    });
  }
  _toFormData() {
    const fd = new FormData();
    Object.entries(this.data).forEach(([key, value]) => {
      if (value instanceof File) {
        fd.append(key, value);
      } else if (typeof value === 'object') {
        fd.append(key, JSON.stringify(value));
      } else {
        fd.append(key, value);
      }
    });
    return fd;
  }
  _toXML() {
    let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<form>\n';
    this._buildXML(this.data, xml, 1);
    xml += '</form>';
    return xml;
  }
  _buildXML(obj, xml, indent) {
    const space = '  '.repeat(indent);
    Object.entries(obj).forEach(([key, value]) => {
      if (typeof value === 'object' && !Array.isArray(value)) {
        xml += `${space}<${key}>\n`;
        this._buildXML(value, xml, indent + 1);
        xml += `${space}</${key}>\n`;
      } else {
        xml += `${space}<${key}>${value}</${key}>\n`;
      }
    });
    return xml;
  }
}
// 使用示例
const builder = new AdvancedFormBuilder({
  name: { required: true, maxLength: 50 },
  contact: {
    email: { type: 'email' },
    phone: { type: 'phone' }
  },
  tags: { type: 'array' }
});
builder
  .set('name', '测试用户')
  .set('contact.email', 'test@example.com')
  .setArray('tags', ['tag1', 'tag2'])
  .addArrayItem('tags', 'tag3');
const formData = builder.generate();
console.log('URL 编码:', formData.toUrlEncoded());
console.log('原始数据:', formData.data);

测试用表单数据生成器

class TestFormDataGenerator {
  constructor() {
    this.fieldGenerators = {
      string: (options = {}) => {
        const chars = 'abcdefghijklmnopqrstuvwxyz';
        const length = options.length || 10;
        return Array.from({ length }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
      },
      number: (options = {}) => {
        const min = options.min || 0;
        const max = options.max || 9999;
        return Math.floor(Math.random() * (max - min + 1)) + min;
      },
      email: () => `${this.fieldGenerators.string({ length: 8 })}@${this.fieldGenerators.string({ length: 5 })}.com`,
      phone: () => `1${Array.from({ length: 10 }, () => Math.floor(Math.random() * 10)).join('')}`,
      date: (options = {}) => {
        const start = options.startDate || '2020-01-01';
        const end = options.endDate || '2024-12-31';
        const startMs = new Date(start).getTime();
        const endMs = new Date(end).getTime();
        return new Date(startMs + Math.random() * (endMs - startMs)).toISOString().split('T')[0];
      },
      boolean: () => Math.random() > 0.5,
      file: () => new File(['test content'], `test_${Date.now()}.txt`, { type: 'text/plain' })
    };
  }
  // 根据 schema 生成随机表单数据
  generateFromSchema(schema) {
    const data = {};
    Object.entries(schema).forEach(([field, config]) => {
      if (config.type === 'group') {
        data[field] = this.generateFromSchema(config.fields);
      } else if (config.type === 'array') {
        data[field] = Array.from(
          { length: config.count || 3 },
          () => this.generateFromSchema(config.itemSchema || {})
        );
      } else {
        const generator = this.fieldGenerators[config.type];
        if (generator) {
          data[field] = generator(config.options || {});
        }
      }
    });
    return data;
  }
  // 生成多个测试用例
  generateTestCases(schema, count = 5) {
    return Array.from({ length: count }, (_, index) => ({
      case: index + 1,
      data: this.generateFromSchema(schema),
      timestamp: new Date().toISOString()
    }));
  }
}
// 使用示例
const generator = new TestFormDataGenerator();
const schema = {
  username: { type: 'string', options: { length: 8 } },
  age: { type: 'number', options: { min: 18, max: 65 } },
  email: { type: 'email' },
  phone: { type: 'phone' },
  birthDate: { type: 'date' },
  isActive: { type: 'boolean' },
  avatar: { type: 'file' },
  address: {
    type: 'group',
    fields: {
      street: { type: 'string', options: { length: 20 } },
      city: { type: 'string', options: { length: 10 } }
    }
  },
  tags: {
    type: 'array',
    count: 3,
    itemSchema: {
      name: { type: 'string', options: { length: 5 } }
    }
  }
};
const testCases = generator.generateTestCases(schema, 3);
console.log('测试用例:', JSON.stringify(testCases, null, 2));

使用建议

  1. 基础场景:使用第一个简单的 FormDataBuilder
  2. 复杂嵌套:使用 AdvancedFormBuilder
  3. 测试目的:使用 TestFormDataGenerator

这些脚本可以直接在浏览器或 Node.js 环境中使用,支持:

  • 字段验证
  • 多种输出格式(JSON、FormData、URL编码、XML)
  • 文件上传支持
  • 随机测试数据生成
  • 链式调用

根据你的具体需求选择合适的实现方式。

抱歉,评论功能暂时关闭!