You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Angular中创建带动态验证的动态表单字段

动态表单字段生成与验证解决方案

下面提供两种主流实现方案,分别基于Vue 3框架(推荐,开发效率更高)和原生JavaScript(无依赖场景适用),均可满足你根据字段配置动态生成表单并实现必填、最大长度验证的需求。


方案一:Vue 3 + 原生逻辑验证

1. 准备字段配置数据

const formFields = [
  {
    sno: 1,
    name: "name",
    nameLabel: "Name",
    isRequired: 1,
    maxLen: 50,
    order: 1,
  },
  {
    sno: 2,
    name: "desc",
    nameLabel: "Description",
    isRequired: 1,
    maxLen: 50,
    order: 2,
  }
];

2. 动态渲染表单模板

<template>
  <form @submit.prevent="handleSubmit">
    <!-- 按order值排序渲染字段 -->
    <div 
      v-for="field in formFields" 
      :key="field.sno" 
      class="form-item"
      :style="{ order: field.order }"
    >
      <label :for="field.name">
        {{ field.nameLabel }}
        <span v-if="field.isRequired === 1" class="required-mark">*</span>
      </label>
      <input 
        :id="field.name"
        v-model="formData[field.name]"
        :maxlength="field.maxLen"
        type="text"
        :class="{ 'input-error': errors[field.name] }"
      >
      <span class="error-text" v-if="errors[field.name]">{{ errors[field.name] }}</span>
    </div>
    <button type="submit" class="submit-btn">提交</button>
  </form>
</template>

3. 实现动态验证逻辑

<script setup>
import { ref } from 'vue';

const formFields = [/* 上述字段配置数据 */];
const formData = ref({});
const errors = ref({});

const handleSubmit = () => {
  // 重置错误信息
  errors.value = {};
  let isFormValid = true;

  // 遍历字段逐一校验
  formFields.forEach(field => {
    const inputValue = formData.value[field.name]?.trim() || '';
    
    // 必填校验
    if (field.isRequired === 1 && !inputValue) {
      errors.value[field.name] = `${field.nameLabel} 为必填项`;
      isFormValid = false;
    }
    // 最大长度校验
    else if (inputValue.length > field.maxLen) {
      errors.value[field.name] = `${field.nameLabel} 长度不能超过 ${field.maxLen} 个字符`;
      isFormValid = false;
    }
  });

  // 校验通过则执行提交逻辑
  if (isFormValid) {
    console.log('表单数据合法,提交内容:', formData.value);
    // 替换为实际接口请求或其他提交操作
  }
};
</script>

4. 基础样式补充

<style scoped>
.form-item {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.required-mark {
  color: #ff4d4f;
  margin-left: 4px;
}
.input-error {
  border: 1px solid #ff4d4f;
}
.error-text {
  color: #ff4d4f;
  font-size: 12px;
}
.submit-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>

方案二:原生JavaScript实现(无框架依赖)

1. HTML基础结构

<form id="dynamicForm">
  <div id="fieldContainer"></div>
  <button type="submit" class="submit-btn">提交</button>
</form>

2. 动态生成表单与验证逻辑

const formFields = [/* 字段配置数据 */];
const fieldContainer = document.getElementById('fieldContainer');
const form = document.getElementById('dynamicForm');

// 渲染动态表单字段
function renderFields() {
  fieldContainer.innerHTML = '';
  formFields.forEach(field => {
    const itemWrapper = document.createElement('div');
    itemWrapper.className = 'form-item';
    itemWrapper.style.order = field.order;

    // 生成标签
    const label = document.createElement('label');
    label.htmlFor = field.name;
    label.textContent = field.nameLabel;
    if (field.isRequired === 1) {
      const requiredSpan = document.createElement('span');
      requiredSpan.className = 'required-mark';
      requiredSpan.textContent = '*';
      label.appendChild(requiredSpan);
    }

    // 生成输入框
    const input = document.createElement('input');
    input.id = field.name;
    input.name = field.name;
    input.maxLength = field.maxLen;
    input.type = 'text';

    // 生成错误提示
    const errorEl = document.createElement('span');
    errorEl.className = 'error-text';

    itemWrapper.appendChild(label);
    itemWrapper.appendChild(input);
    itemWrapper.appendChild(errorEl);
    fieldContainer.appendChild(itemWrapper);
  });
}

// 表单验证函数
function validateForm() {
  let isValid = true;
  const errorElements = document.querySelectorAll('.error-text');
  // 清空之前的错误提示
  errorElements.forEach(el => el.textContent = '');

  formFields.forEach(field => {
    const input = document.getElementById(field.name);
    const value = input.value.trim();
    const errorEl = input.nextElementSibling;

    if (field.isRequired === 1 && !value) {
      errorEl.textContent = `${field.nameLabel} 为必填项`;
      isValid = false;
    } else if (value.length > field.maxLen) {
      errorEl.textContent = `${field.nameLabel} 长度不能超过 ${field.maxLen} 个字符`;
      isValid = false;
    }
  });
  return isValid;
}

// 初始化表单
renderFields();

// 监听表单提交
form.addEventListener('submit', function(e) {
  e.preventDefault();
  if (validateForm()) {
    const formData = new FormData(this);
    const submitData = Object.fromEntries(formData);
    console.log('表单提交数据:', submitData);
    // 执行实际提交逻辑
  }
});

3. 基础样式

.form-item {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.required-mark {
  color: #ff4d4f;
  margin-left: 4px;
}
.error-text {
  color: #ff4d4f;
  font-size: 12px;
}
.submit-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

内容的提问来源于stack exchange,提问作者user3653474

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:25:35