Home Web Front-end Vue.js How to use Vue and Element-UI to implement complex validation logic of forms

How to use Vue and Element-UI to implement complex validation logic of forms

Jul 22, 2023 am 08:15 AM
vue form logic element-ui Complex verification

How to use Vue and Element-UI to implement complex validation logic of forms

Introduction:
In developing web applications, form validation is a frequently occurring requirement. Form validation can ensure that user-entered data conforms to specific formats or rules, thereby improving data accuracy and application stability. This article will introduce how to use Vue and Element-UI to implement complex validation logic of forms, and provide readers with relevant code examples.

1. Introduction to Element-UI
Element-UI is a desktop component library developed based on Vue.js. It provides a series of easy-to-use and beautiful UI components, such as tables, forms, Buttons etc. Element-UI has many built-in form verification functions, which can easily implement simple verification logic.

2. The basic principle of form verification
The basic principle of form verification is to obtain the value input by the user by monitoring the change event of the form element, and then verify it according to a series of preset rules. If the verification passes, the status of the form element will be changed to "Verification Passed", otherwise an error message will be displayed and the status of the form element will be changed to "Verification Failed".

3. Use Element-UI for simple form verification
First, we need to introduce the Form and FormItem components of Element-UI, and then use these components in the Vue template to build the form. In the specified form element, you can define validation rules by setting the rules attribute, as shown below:


The form object in the data is stored in the form The value of each input box, and the rules object defines the validation rules for each input box.

In Vue's data, we can define form and rules objects as follows:

data() {
return {

form: {
  username: '',
  password: ''
},
rules: {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
  ]
}
Copy after login

}
}
In the rules object, you can define multiple verification rules, such as required, length limit, etc. The message attribute defines the error message, and the trigger attribute defines the event triggered by the verification.

In Vue's methods, we can define the method validateForm to verify the form. The code is as follows:

methods: {
validateForm() {

this.$refs.myForm.validate((valid) => {
  if (valid) {
    this.$message({
      type: 'success',
      message: '表单校验通过'
    })
  } else {
    this.$message.error('表单校验失败')
    return false
  }
})
Copy after login

}
}
In the validateForm method, we call this.$refs.myForm.validate() method to trigger the verification of the form. The verification result is passed through the callback function valid. If the verification passes, a success message will be displayed, otherwise a failure message will be displayed.

4. Implement complex verification logic
Sometimes, we need to implement more complex verification logic, such as comparing whether the values ​​​​of two input boxes are equal, verifying email addresses, verifying mobile phone numbers, etc. In this case, we can use custom validation rules.

First, in Vue's data, we can define custom verification rules, as shown below:

data() {
return {

rules: {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: this.validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: this.validateConfirmPassword, trigger: 'blur' }
  ]
}
Copy after login

}
}
In the rules object, we can define custom verification rules, where the validator attribute defines the verification function.

Then, in Vue’s methods, we can define a custom validation function, as shown below:

methods: {
validatePassword(rule, value, callback) {

if (value.length < 6 || value.length > 20) {
  callback(new Error('密码长度在6到20个字符'))
} else {
  callback()
}
Copy after login

},
validateConfirmPassword(rule, value, callback) {

if (value !== this.form.password) {
  callback(new Error('两次输入的密码不一致'))
} else {
  callback()
}
Copy after login

}
}
In the custom verification function, we can call the callback function callback to pass the verification results. If the verification passes, callback() is called, otherwise callback(new Error('error message')) is called.

Finally, use custom validation rules in the Vue template, as shown below:









In custom validation rules, we can use the type attribute to specify the built-in validation rules of Element-UI, such as Email rules can be implemented by setting the type attribute to 'email'.

Summary:
This article introduces how to use Vue and Element-UI to implement the complex verification logic of the form. Through the Form and FormItem components provided by Element-UI, we can easily build forms and define validation rules by setting the rules attribute. For complex verification logic, we can implement custom verification rules and verification functions. I hope this article will be helpful for everyone to understand and use Vue and Element-UI for form verification.

Code sample:
The following is a complete sample code:

<script><br>export default {<br> data() {</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>return { form: { username: '', password: '' }, rules: { username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 10, message: '长度在3到10个字符', trigger: 'blur' } ], password: [ { required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' } ] } }</pre><div class="contentsignin">Copy after login</div></div><p>},<br> methods: {</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>validateForm() { this.$refs.myForm.validate((valid) =&gt; { if (valid) { this.$message({ type: 'success', message: '表单校验通过' }) } else { this.$message.error('表单校验失败') return false } }) }</pre><div class="contentsignin">Copy after login</div></div><p>}<br>}<br></script>

以上就是使用Vue和Element-UI实现表单的复杂校验逻辑的一些简单介绍和代码示例。希望本文对于读者能够有所帮助,对于Vue和Element-UI有更深层次的理解和应用。谢谢阅读!

The above is the detailed content of How to use Vue and Element-UI to implement complex validation logic of forms. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with &lt;div&gt;. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

How to use vue pagination How to use vue pagination Apr 08, 2025 am 06:45 AM

Pagination is a technology that splits large data sets into small pages to improve performance and user experience. In Vue, you can use the following built-in method to paging: Calculate the total number of pages: totalPages() traversal page number: v-for directive to set the current page: currentPage Get the current page data: currentPageData()

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the &lt;script&gt; tag in the HTML file that refers to the Vue file.

See all articles