当 q-field 有验证错误时如何防止 Quasar q-form 提交?

How to prevent Quasar q-form submit when q-field has validation error?

我正在尝试实施 vue-phone-input by wrapping it with a Quasar q-field

大部分时间都在工作。输入工作正常,并在输入下方显示验证错误。

问题是即使出现验证错误我也可以提交表单。

如何防止这种情况发生?

通常当 q-formq-inputq-btn 一起使用时,它会自动阻止这种情况的发生。

那么,为什么它在 q-fieldvue-tel-input 中不起作用?

<template>
  <q-form @submit="handlePhoneSubmit">
    <q-field
      v-if="isEditingPhone"
      autocomplete="tel"
      label="Phone"
      stack-label
      :error="isPhoneError"
      error-message="Please enter a valid phone number."
      outlined
      hide-bottom-space
    >
      <vue-tel-input
        v-model="phoneInput"
        @validate="isPhoneError = !isPhoneError"
      ></vue-tel-input>
    </q-field>
    <q-btn
      color="primary"
      text-color="white"
      no-caps
      unelevated
      style="max-height: 56px"
      type="submit"
      label="Save"
      @submit="isEditingPhone = false"
    />
  </q-form>
</template>

<script setup lang="ts">
import { ref, Ref } from 'vue';
import { VueTelInput } from 'vue-tel-input';
import 'vue-tel-input/dist/vue-tel-input.css';

const phone: Ref<string | null> = ref('9999 999 999');
const isEditingPhone = ref(true);
const isPhoneError = ref(false);
const phoneInput: Ref<string | null> = ref(null);
const handlePhoneSubmit = () => {
  phone.value = phoneInput.value;
  console.log('Form Saved');
};
</script>

首先,您应该使用 Quasar 的 :rules 系统,而不是 :error@validate

<q-field :rules="[checkPhone]" 

function checkphone(value: string) {
  return // validate the value here
}

然后,如果提交还不够,您可能需要在 <q-form 上设置一个 ref,然后调用它的 validate() 方法。

这里是操作方法(我删除了部分代码以突出显示需要的内容)。

<template>
  <q-form ref="qform" @submit="handlePhoneSubmit">
  //..
  </q-form>
</template>

<script setup lang="ts">
import { QForm } from "quasar";
import { ref } from "vue";

//..

const qform = ref<QForm|null>(null);

async function handlePhoneSubmit() {
  if (await qform.value?.validate()) {
    phone.value = phoneInput.value;
  }
}