Official document: http://vuejs.github.io/vue-validator/zh-cn/index.html
github project address: https:// github.com/vuejs/vue-validator
See the official documentation for how to use vue-validator alone. This article is used in combination with vue-router.
Install validator
Do not add a custom validator or a public validator that does not need to be used globally, install the validator in main.js , using the CommonJS module specification, you need to explicitly use Vue.use() to install the validator component.
import Validator from 'vue-validator' Vue.use(Validator)
When used together with vue-router, verification must be installed before calling router#map, router#start and other instance methods.
To customize the validator, create a js file and install the validator component in the file. For example: validation.js
import Vue from 'vue' import Validator from 'vue-validator' Vue.use(Validator) //自定义验证器
Custom validator
The official api provided is as follows
input[type="text"] input[type="radio"] input[type="checkbox"] input[type="number"] input[type="password"] input[type="email"] input[type="tel"] input[type="url"] select textarea
But the above does not It must meet our needs. At this time, we need to use another global API for registering and obtaining global validators.
Vue.validator( id, [definition] )
Example Define validation.js The content is as follows
import Vue from 'vue' import Validator from 'vue-validator' Vue.use(Validator) //自定义验证器 //添加一个简单的手机号验证 //匹配0-9之间的数字,并且长度是11位 Vue.validator('tel', function (val) { return /^[0-9]{11}$/.test(val) }); //添加一个密码验证 //匹配6-20位的任何字类字符,包括下划线。与“[A-Za-z0-9_]”等效。 Vue.validator('passw', function (val) { return /^(\w){6,20}$/.test(val) });
Use validator
Validator syntax
<validator name="validation"> <input type="text" v-model='comment' id='comment' v-validate:comment="{ minlength: 3, maxlength: 15 }"> <div> <span v-show="$validation.comment.minlength">不得少于3个字符</span> <span v-show="$validation.comment.maxlength">不得大于15个字符</span> </div> </validator>
By default, vue-validator will automatically verify based on the validator and v-validate instructions. However, sometimes we need to turn off automatic verification and trigger verification manually when necessary. If you don't need automatic validation, you can turn off automatic validation through the initial attribute or the v-validate validation rule.
is as follows:
<validator name="validation"> <input type="text" v-model='comment' id='comment' v-validate:comment="{ minlength: 3, maxlength: 15 }" detect-change="off" initial='off'> <div> <span v-show="$validation.comment.minlength">不得少于3个字符</span> <span v-show="$validation.comment.maxlength">不得大于15个字符</span> </div> </validator>
Terminal command problem
<validator name="test_validator"> <!-- @invalid:valid的逆 ,表示验证不通过 --> <input @invalid="passwInvalid" @valid="passwok" type="password" v-model='passw' id='passw' v-validate:passw="['passw']" detect-change="off" initial='off' placeholder='请输入密码'> <input @invalid="passwInvalid" @valid="passwok" type="password" v-model='passw2' id='passw2' v-validate:passw2="['passw']" detect-change="off" initial='off' placeholder='请输入密码'> </validator> <script> //若是在main.js中导入 无需再次导入 //此处导入的是上面代码的validation.js import validator from '../validator/validation' export default{ data(){ return{ comment:'', passw:'', passw2:'' } }, methods:{ passwInvalid(){ alert('只能输入6-20个字母、数字、下划线'); }, passwok(){ //alert('验证码符合规范') } } } </script>
Example: User registration verification
is used A component to display prompt information
toast.vue
<template> <div v-show="toastshow" transition="toast" class="toast font-normal"> {{toasttext}} </div> </template> <script> export default{ props:{ //是否显示提示 toastshow:{ type:Boolean, required: false, default:function(){ return false; } }, //提示的内容 toasttext:{ type:String, required: false, default:function(){ return 'no message'; } }, //显示的时间 duration: { type: Number, default:3000,//默认3秒 required:false } }, ready() { }, watch:{ toastshow(val){ if (this._timeout) clearTimeout(this._timeout) if (val && !!this.duration) { this._timeout = setTimeout(()=> this.toastshow = false, this.duration) } } } } </script> <style> .toast{ position:absolute; left:50%; margin-left:-25%; bottom:30px; display:block; width:200px; height:auto; text-align:center; color:white; background-color:rgba(0,0,0,0.5); border-radius:10px; z-index:10; transform:scale(1); padding:5px; } .toast-transition{ transition: all .3s ease; } .toast-enter{ opacity:0; transform:scale(0.1); } .toast-leave{ opacity:0; transform:scale(0.1); } </style>
Registered user: If we need to fill in the mobile phone number and enter the password twice
<template> <div class='register-box'> <!-- 组件:用于显示提示信息 --> <Toast :toastshow.sync="toastshow" :toasttext="toasttext"></Toast> <validator name="validation_register1"> <div class='register1'> <div class='pd05'> <input @invalid="telonInvalid" initial="off" detect-change="off" v-model="telphone" id="telphone" type="tel" class='phone-number' v-validate:telphone="['tel']" placeholder='请输入手机号码'> </div> <div class='pd05'> <input @invalid="passwInvalid" v-model="passw1" initial="off" detect-change="off" id="passw1" type="password" v-validate:passw1="['passw']"class='password-number'placeholder='请输入密码'> </div> <div class='pd05'> <input @invalid="passwInvalid" v-model="passw2" initial="off" detect-change="off" id="passw2" type="password" v-validate:passw2="['passw']" class='password-number' placeholder='请输入密码'> </div> <a class='greenBtn' v-on:click='register_user()'>下一步</a> </div> </validator> </div> </template> <script> //导入validation.js 此处的validation.js就是上文中validation.js的内容 import validator from '../validator/validation'; //导入显示提示信息的组件 import Toast from '../components/toast.vue'; export default{ components: { //注册组件 Toast }, data(){ return{ telphone:'',//电话号码 toastshow:false,//默认不现实提示信息 toasttext:'',//提示信息内容 passw1:'',//首次输入密码 passw2:''//再次输入密码 } }, methods:{ //手机号验证失败时执行的方法 telonInvalid(){ //设置提示信息内容 this.$set('toasttext','手机不正确'); //显示提示信息组件 this.$set('toastshow',true); }, //密码验证失败时执行的方法 passwInvalid(){ this.$set('toasttext','只能输入6-20个字母、数字、下划线'); this.$set('toastshow',true); }, register_user(){ var that = this; var telephones = that.$get('telphone'); var pw1 = that.$get('passw1'); var pw2 = that.$get('passw2') that.$validate(true, function () { if (that.$validation_register1.invalid) { //验证无效 that.$set('toasttext','请完善表单'); that.$set('toastshow',true); }else{ that.$set('toasttext','验证通过'); that.$set('toastshow',true); //验证通过做注册请求 /*that.$http.post('http://192.168.30.235:9999/rest/user/register', 'account':telephones,'pwd':pw1,'pwd2':pw2}).then(function(data){ if(data.data.code == '0'){ that.$set('toasttext','注册成功'); that.$set('toastshow',true); }else{ that.$set('toasttext','注册失败'); that.$set('toastshow',true); } },function(error){ //显示返回的错误信息 that.$set('toasttext',String(error.status)); that.$set('toastshow',true); })*/ } }) } } } </script> <style> .register-box{ padding: 10px; } .pd05{ margin-top: 5px; } .greenBtn{ width: 173px; height: 30px; text-align: center; line-height: 30px; background: red; color: #fff; margin-top: 5px; } </style>
If you click next step, you will be prompted "Please complete the form" because the verification fails; if the text box loses focus after gaining focus, a corresponding error message will be prompted; if the content is filled in correctly, it will prompt that the verification has passed and send a corresponding request.
The effect is as shown
Related recommendations:
2020 Summary of front-end vue interview questions (With answers)
vue tutorial recommendation: The latest 5 vue.js video tutorial selections in 2020
More programming-related knowledge, Please visit: Introduction to Programming! !
The above is the detailed content of Detailed explanation of the use of vue validator (vue-validator). For more information, please follow other related articles on the PHP Chinese website!

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.