Ant Design Vue表单验证基本操作

x33g5p2x  于2022-02-18 转载在 Ant Design  
字(1.6k)|赞(0)|评价(0)|浏览(567)

通过 rules 属性传入约定的验证规则。并将 <a-form-item> 的 prop 属性设置为需校验的字段名即可

formRef.value .validate()  触发效验提示通过进入then,否则进入catch

formRef.value.resetFields() 清空效验红色提示

labelCol: label 标签布局,同 <Col> 组件,设置 span offset 值,如 {span: 3, offset: 12} 或 sm: {span: 3, offset: 12}

<a-form
      ref="formRef"  //表单验证会用上这个变量
      :model="formState"  //表单数据对象
      :rules="rules"      //表单验证规则
      :label-col="labelCol"
      :wrapper-col="wrapperCol"  //为输入控件设置布局样式时,使用该属性,用法同 labelCol
    >
      <a-form-item :label="a1" name="name">// name表单名称,会作为表单字段 id 前缀使用
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item v-if="a2" :label="a2" name="name2">
        <a-input-password
          autocomplete="new-password"
          v-model:value="formState.name2"
        />
      </a-form-item>
</a-form>

<script>
    const formRef = ref();
const formState = ref({
      name: "",
      name5: "",
      name2: "",
    });
   const rules = {//里面写效验规则
      name: {
        required: true,  //是否必填项,设置红色星号
        min: 3,                //最短3个字符
        max: 36,                //最长36个字符
        message: "用户名长度需为3~36之间",  //提示语
      },
      name2: {
        max: 22,
        min: 6,
        required: true,
        pattern: new RegExp(
          /((?=.*\d)(?=.*\D)|(?=.*[a-zA-Z])(?=.*[^a-zA-Z]))(?!^.*[\u4E00-\u9FA5].*$)^\S{6,22}$/
        ),  //写入正则效验
        message: "密码至少包含数字,字母和字符的两种组合,长度在6-22之间",
      },
}
   const diaoyong = () => {
      // 表单验证  validate触发表单验证,验证不通过会阻断后续操作
      formRef.value
        .validate()
        .then(() => {
          if (data.value) {
            bianji();
          } else {
            chuangjian();
          }
          console.log("values", formState, toRaw(formState));
        })
        .catch((error) => {
          console.log("error", error);
        });
    };
return {
      formRef,
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
      formState,
      diaoyong,
      rules,
    };
</script>

相关文章