vue中用js验证input框中的手机号、密码、邮箱等

注:

    1、本文的input框为<input></input>,不是<el-input></el-input>。

    2、绑定blur方法使用@blur,不可用onblur(会报错)

一、html部分:

<template>
  <div>
    <!--手机号-->
    <div class="error">
       <div class="input-fill-x" >
           <input v-model="param.account" class="input-control input-fill" 
                  placeholder="手机号码"
                  id="telephone" @blur="checkPhone()" >
            <label class="input-label">手机号码</label>
        </div>
        <div class="errorDiv">{
   
   {s_telephone1}}</div>
    </div>
    <!--密码-->
    <div class="error">
       <div class="input-fill-x" >
           <input v-model="param.password" class="input-control input-fill" 
                  placeholder="密码"
                  :type="pwdType===true ?'password' :'text' " id="password" 
                  @blur="checkPasswords()">
              <label class="input-label">密码</label>
        </div>
        <div class="errorDiv">{
   
   {s_password1}}</div>
    </div>    
  </div>
</template>

其中:<div class="errorDiv">{ {s_telephone1}}</div>的{ {s_telephone1}}为错误提示信息

二、js部分

<script>

export default {
  name: 'UserLogin',  //vue的name
  data() {
    return {
      param: {
      }
      s_telephone1:"",//手机号错误提示信息初始为空
      s_password1:"",//密码错误提示信息初始为空
    };
  },
  methods:{    
        //手机号1校验
        checkPhone(){
          //定义phone,通过唯一id拿到input框输入的值
          const phone = document.getElementById('telephone').value; 
          if(!(/^1[34578]\d{9}$/.test(phone))) {  //手机号正则校验
            if(phone===''){ //若手机号为空
              this.s_telephone1 = "请输入手机号码";
              return false;
            }else { //手机号非空的报错信息
              this.s_telephone1 = "手机号码格式错误";
              return false;
            }
          }else{ //手机号正确则无错误信息
            this.s_telephone1 = "";
            return true;
          }
        },
        // 密码校验
        checkPasswords(){  
          //定义password,通过唯一id拿到input框输入的值
          const password = document.getElementById('password').value;   
          if(!(/^[a-zA-Z][a-zA-Z0-9]{7,19}$/.test(password))){ //密码正则校验
            if(password===''){ //若密码为空
              this.s_password1 = "请输入登录密码";
              return false;
            }else { //密码非空的报错信息
              this.s_password1 = "密码8-20位,包含字母和数字,字母开头,不可以有特殊符号";
              return false;
            }
          }else{ //密码正确则无错误信息
            this.s_password1 = "";
            return true;
          }
        },

  },
}

</script>

三、实现效果

1、未进行任何操作

2、点击手机号码input框,但未输入任何信息

 

扫描二维码关注公众号,回复: 15613643 查看本文章

 3、点击手机号码input框,输入错误信息

参考:

https://jingyan.baidu.com/article/b907e62797e19146e7891ccb.html

HTML表单验证(含用户名,密码,邮箱,手机号,验证码-验证)_狙个栗子的博客-CSDN博客_html表单验证

题外话:

在vue中用input、lable是为了实现input动画效果,与本文无关了,有时间再写,实现效果类似小米登陆官网:小米帐号 - 登录 (xiaomi.com)

略微类似下文写法,感兴趣可看

一个好看的input输入动画_千秋,的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_45991812/article/details/127512742