el-input输入11位手机号,边输入边验证手机号码格式

喉咙痛…不多说,直接上码
den…gdeng…不对,喉咙痛和打字什么关系…
哎…反正多写也无益,少写也许喉咙就好了呢…

<template>
	<el-form :rules="rules" :model="data">
		<el-form-column prop="phone">
			<el-input @input="phoneChange" v-model="data.phone"></el-input>
		</el-form-column>
	</el-form>
</template>

<script>
export default{
	data(){
		let checkPhone:(rule,value,callback)=>{
			var reg=/^1[3456789]\d{9}$/;
			if(reg.test(value)){
				callback(new Error("请输入正确的手机号码格式"));
			}else{
				callback();
			}
		}
		return{
			data:{
				phone:""
			},
			rules:{
				phone:[{validator:checkPhone,required:true,trigger:"blur"}]
			}
		}
	},
	methods:{
		phoneChange(){
			this.data.phone=this.data.phone.replace(/[^\d]/g,"");
			if(this.data.phone.length>11){
				this.data.phone=this.data.phone.substr(0,11);
			}
			//如果依赖element的表单校验,就到这里就OK了,如果单单用了el-input不用element的表单校验,那继续往下
			var reg=/^1[3456789]\d{9}$/;
			if(this.data.phone.length>=11 && !reg.test(this.data.phone)){
				alert("请输入正确的手机号码格式")
			}
		}
	}
}
</script>

你可能感兴趣的:(element,Vue)