【问题标题】:how to stop form submitting if form is invalid in vue3 cli compostion apis in vee validate如果表单在 vee validate 中的 vue 3 cli composition apis 中无效,如何停止表单提交
【发布时间】:2021-01-24 20:26:12
【问题描述】:

我是 vue3 和组合 API 的新手。 验证简单表单存在问题。 如果表单无效或未触摸,我将尝试停止表单提交,因为如果未触摸输入,默认情况下它是有效的。

登录.vue

<form @submit="onSubmit">
  <div class="form-group">
    <input
      name="email"
      type="text"
      v-model="email"
    />
    <span>{{ emailError }}</span>
  </div>
  <div class="form-group">
    <input
      name="password"
      type="password"
      v-model="password"
    />
    <span>{{ passwordError }}</span>
  </div>
  <div class="login-buttons">
    <button
      type="submit"
    >
      {{ $t("login.login") }}
    </button>
  </div>
</form>

login.js

<script>
import { useForm, useField,useIsFormValid } from "vee-validate";
import * as yup from "yup";

export default {
  name: "LoginPage",
  setup() {
    const {
      errors,
      handleSubmit,
      validate,
    } = useForm();


    // Define a validation schema
    const schema = yup.object({
      email: yup
        .string()
        .required()
        .email(),
      password: yup
        .string()
        .required()
        .min(8),
    });

    // Create a form context with the validation schema
    useForm({
      validationSchema: schema,
    });

    // No need to define rules for fields
    const { value: email, errorMessage: emailError } = useField(
      "email"
    );
    const { value: password, errorMessage: passwordError } = useField(
      "password"
    );

    const onSubmit = handleSubmit(async () => {
      const { valid, errors } = await validate();
      if (valid.value === false) {
        return;
      } else {
        const response = await http.post(APIs.login, data);
      }
    });

    return {
      email,
      emailError,
      password,
      passwordError,
      onSubmit
    };
  },
};
</script>

在handelSubmit 函数中,if (vaild.value === false) 应该返回并停止逻辑,但 vaild 的值始终为 true,因此它会继续对 api 进行 HTTP 调用。

仅当表单使用组合 API 无效时才停止向表单发送数据

【问题讨论】:

    标签: composition vue-cli-3 vee-validate


    【解决方案1】:

    您使用useForm 创建了两个表单,并且基本上使用了第一个未定义任何规则的提交处理程序。

    删除第二个useForm 调用并将规则传递给第一个。

    const schema = yup.object({
      email: yup.string().required().email(),
      password: yup.string().required().min(8),
    });
    
    const { errors, handleSubmit, validate } = useForm({
      validationSchema: schema
    });
    

    【讨论】:

    • 谢谢。我注意到了,但忘记在 stackoverflow 上更新我的答案。
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2019-08-13
    • 2021-07-18
    相关资源
    最近更新 更多