Vue verifies the mobile phone number and the landline number at the same time

Preface

Recently I encountered form validation, which is to verify whether it is a mobile phone number and a landline number. If so, the verification will pass. If not, a text prompt will appear. Because I am not very proficient in this part, I wrote a note to record it so that I will not forget or get confused later.

Business scene

If the mobile phone number is in the form of 1xx-xxxx-xxxx, and the landline number is in the form of 0xxx-xxxxxxxx (where x represents a number), it will pass the verification of the contact number. If it is in other formats, it will not pass the verification.

solve

Here is the code for the form, with rules bound to it.

 <el-col :span="8">
    <el-form-item label="联系电话:" prop="telephone" label-width="160px" >
       <el-input v-model="form.telephone" type="text"></el-input>
    </el-form-item>
 </el-col>

Then add the contact phone number rule in the rules, and write the parameters defined by the verification rule declared above in the validator. What I wrote here is checkPhone. Pay attention to uniformity. Then there is verification of mobile phone number and landline number in checkPhone.

data(){ 
var checkPhone = (rule, value, callback) => {
    if (value === '') {
    callback(new Error('联系电话不可为空!'));
    } else {
      let regPone = null;
      let mobile = /^1(3|4|5|6|7|8|9)\d{9}$/; //最新16手机正则
      let tel = /^(0\d{2,3}-){0,1}\d{7,8}$/; //座机
      if (value.charAt(0) == 0) {   // charAt查找第一个字符方法,用来判断输入的是座机还是手机号
        regPone = tel;
      } else {
        regPone = mobile;
      }
      if (!regPone.test(value)) {
        callback(new Error("请输入正确的电话格式!"))
      }
      callback();
    }
   }
return{
   rules: {
     telephone: [
          {
            required: true,
            trigger: "blur",
            validator: checkPhone
          }
        ],
   }
 }
}

Guess you like

Origin blog.csdn.net/m0_59360516/article/details/127752678