0

i am new to vue3 and composition apis. there is problem with validating a simple form. i am trying to stop form submission if form is not valid or not touched as it is vaild by default if inputs not touched.

login.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>

in handelSubmit function if (vaild.value === false) it should return and stop the logic but always the value for vaild is true so it continues the HTTP calling for the api.

only wan't to stop sending data to the if the form is invaild using composition apis

1 Answer 1

0

You created two forms with useForm and basically using the submit handler of the first one that doesn't define any rules.

Remove the second useForm call and pass the rules to the first one.

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

const { errors, handleSubmit, validate } = useForm({
  validationSchema: schema
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I noted that but forget to update my answer on stackoverflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.