Home  >  Article  >  Web Front-end  >  How to implement form data verification under Vue?

How to implement form data verification under Vue?

王林
王林Original
2023-06-27 09:39:232581browse

Vue is a very powerful front-end framework that provides many features to help us quickly develop a full-featured web application. These include form data validation, a very important feature that ensures that the data entered by users is legal, valid, and expected. Vue provides several different methods to implement form data validation, and this article will introduce some of them in detail.

  1. Vue’s own form verification instructions

Vue accepts some built-in instructions and can be used directly in the template to verify the form. These include directives such as v-model, v-bind, and v-on. These instructions can be bound to the data of the Vue instance when processing form values, and can also be used with other instructions to implement more complex form validation.

The following is an example that shows how to use the v-model and v-on directives to check whether the email address in a form input box is valid:

<template>
  <div>
    <input v-model="email" @blur="validateEmail" type="email" name="email" required>
    <div v-if="validEmail === false">请输入一个有效的邮箱地址。</div>
  </div>
</template>

<script>
export default {
  data() {
    // 初始值为空
    return {
      email: '',
      validEmail: null
    };
  },
  methods: {
    validateEmail() {
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/;
      this.validEmail = reg.test(this.email);
    }
  }
}
</script>

In this example, we added the attribute validEmail to the original data to track the execution results of the validateEmail method. Then, we bound the v-model and v-on directives of the input box, as well as the @blur event that is triggered when it loses focus. In the @blur event, the validateEmail() method compares the input value to the regular expression, and if it matches, sets the validEmail property to true; otherwise set to false. Finally, we use the v-if directive to display the error message.

  1. Use plug-ins for form verification

In addition to Vue’s own form verification instructions, we can also use some open source plug-ins to help us implement form verification. One of the most commonly used plugins is VeeValidate. It is a template-based form validation plug-in that provides many validation rules, such as required, email, min_length, etc. In addition, you can customize rules to meet your own business needs.

<template>
  <div>
    <input v-model="email" name="email" v-validate="'required|email'">
    <div v-show="errors.has('email')" class="text-danger">{{ errors.first('email') }}</div>
  </div>
</template>

<script>
import { required, email } from 'vee-validate/dist/rules';
import { extend } from 'vee-validate';
import { ValidationProvider, ValidationObserver, localize } from 'vee-validate';
import zh_CN from 'vee-validate/dist/locale/zh_CN.json';

extend('required', required);

extend('email', email);

localize('zh_CN', zh_CN);

export default {
  data() {
    return {
      email: ''
    };
  },
  components: {
    ValidationProvider,
    ValidationObserver
  }
}
</script>

In this example, we first import the required components and methods in VeeValidate. We then added a v-validate attribute specifying certain instructions to validate the input. The parameters in this directive specify the validation rules to apply, such as required and email. We can also build custom rules using something similar to directives.

  1. Manual form verification

In addition to the built-in instructions and plug-ins, we can also use manual methods to perform form verification. Here is a sample code for manually validating form input in Vue:

<template>
  <div>
    <form @submit.prevent="handleSubmit">
      <input type="text" v-model="username">
      <button type="submit">提交</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: ''
    };
  },
  methods: {
    handleSubmit() {
      if (this.username === '') {
        alert('用户名不能为空!');
        return;
      }

      alert('提交成功!');
    }
  }
}
</script>

In this example, we first use v-model to bind the value of the input box to the component's username attribute. Then, we use @submit.prevent to listen to the form's submission event and implement the handleSubmit method for data validation. In this method, we first check if the username is empty, prompt the user if it is empty, and prevent the form from being submitted. Otherwise, a success message is displayed.

Summary

The above are several ways to verify form data in Vue. Vue's built-in instructions provide simple and fast verification. Using the VeeValidate plug-in, you can implement the definition of form rules efficiently and diversely. Manual form validation is not only cumbersome, but can also easily lead to lengthy code and code maintenance issues. Therefore, it is very important to choose an appropriate form verification method based on actual business needs.

The above is the detailed content of How to implement form data verification under Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn