首页 > 解决方案 > vee-validate@4.x - 如何手动验证字段

问题描述

使用时

我遇到了以下问题:

<Form @submit="onSubmit" :validation-schema="schema">
  <div class="mb-3">
    <label for="edit-email" class="form-label">E-mail</label>
    <Field
      id="edit-email"
      class="form-control"
      name="email"
      type="text"
      :validateOnInput="true"
    />
    <ErrorMessage class="invalid-feedback" name="email" />
  </div>

  <button @click="checkEmail" type="button">Check e-mail address</button>


  <!-- non-important part of the form -->
</Form>

我想手动验证 <Field />单击按钮的时间(应该出现错误消息),然后我想使用该字段value执行另一个操作。

我写了以下代码:

import { useFieldValue } from 'vee-validate';

// setup
setup() {  
    const schema = object({ 
      email: string().required().email().label("e-mail"), 
    });
 
    function verifyEmail(v) {
      const emailValue = useFieldValue("email");
      console.log(emailValue); // empty ComputedRefImpl
    }

    return { 
      schema, 
      verifyEmail,
    };
  },
}

这是行不通的。 以带有值的ComputedRefImplemailValue形式返回。undefined

我想我正在混合 vee-validate 的组件和组合 API 风格。但仍然不知道如何解决这个问题。

使用此创建沙箱:https ://codesandbox.io/s/vue3-vee-validate-form-field-forked-xqtdg?file=/src/App.vue

任何帮助都感激不尽!

标签: javascriptvue.jsvuejs3vee-validate

解决方案


根据 vee-validate 的作者: https ://github.com/logaretm/vee-validate/issues/3371#issuecomment-872969383

useFieldValue 仅用作 useForm 或 useField 的子项。

所以在使用组件时它不起作用<Field />


推荐阅读