VUE-表单验证

2021/8/24 6:07:11

本文主要是介绍VUE-表单验证,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <script src="vue.js"></script>
</head>
<body>
<div id="app">
    <form>
        用户名 <input type="text" name="username" v-model="username">
        手机号 <input type="text" name="mobile" v-model="mobile">
        密码 <input type="password" name="password" v-model="password">
        <button type="button" @click="login" >登录</button>
    </form>
    <p v-for="(v,k) in err_arr">
        {{v}}
    </p>
</div>
</body>
</html>
<script>

    new Vue({
        el:"#app",
        data:{
            auth_user:"zhangsan123",
            auth_pass:"123456",
            auth_mobile:"18518505221",
            username:'',
            password:'',
            mobile:'',
            err_arr:[]
        },
        methods:{
            login(){
                if(this.validate()){
                    alert("登录成功");
                }
            },
            //验证器
            validate(){
                this.err_arr = [];
                if(this.username == ""){
                    this.err_arr.push('用户名不能为空');
                    return false;
                }
                var reg_user = /^[a-zA-Z\u4e00-\u9fa5]\w{6,16}$/;
                if(!reg_user.test(this.username)){
                    this.err_arr.push('用户名格式不正确');
                    return false;
                }

                if(this.mobile == ""){
                    this.err_arr.push('手机号不能为空');
                    return false;
                }
                var reg_mobile = /^1[35678]\d{9}$/;
                if(!reg_mobile.test(this.mobile)){
                    this.err_arr.push('手机号格式不正确');
                    return false;
                }

                if(this.password == ""){
                    this.err_arr.push('密码不能为空');
                    return false;
                }
                var reg_pass = /^\w{6,15}$/;
                if(!reg_pass.test(this.password)){
                    this.err_arr.push('密码格式不正确');
                    return false;
                }

                if(this.auth_mobile == this.mobile  && this.auth_pass == this.password &&  this.auth_user == this.username){
                    this.err_arr = [];
                    return true;
                }else {
                    this.err_arr.push('账号或者密码出错');
                    return false;
                }


            }
        }

    });
</script>

  



这篇关于VUE-表单验证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程