UNPKG

insight-plugin-verifier

Version:

Insight-verifier

166 lines (150 loc) 3.74 kB
/** * 表单验证插件 * * date:2019年1月29日 * author: ZC_阮 */ interface verifierOption { verifyMsg:object; code:number; msg:string; replaceWord:string; } export class Verifier implements verifierOption{ verifyMsg:object = {}; code:number; msg:string; replaceWord:string; constructor(option) { option=option?option:{}; } //非空验证 public empty(value){ if(!value){ this.code = 10010; this.msg = "内容为空"; }else{ this.code = 0; this.msg = "验证通过"; } return this.returnMsg(); } //邮箱验证 public email(value){ let reg = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/); let result = reg.test(value); if(!result){ this.code = 10010; this.msg = "邮箱格式错误"; }else{ this.code = 0; this.msg = "验证通过"; } return this.returnMsg(); } //手机验证 public phone(value){ let reg = new RegExp(/^1(3|4|5|7|8)\d{9}$/); let result = reg.test(value); if(!result){ this.code = 10010; this.msg = "手机格式错误"; }else{ this.code = 0; this.msg = "验证通过"; } return this.returnMsg(); } //身份证验证 public credit(value){ let reg = new RegExp( /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/); let result = reg.test(value); if(!result){ this.code = 10010; this.msg = "身份证格式错误"; }else{ this.code = 0; this.msg = "验证通过"; } return this.returnMsg(); } //账号验证 public account(value,rule=0){ if(rule==1){ //只能输入数字 var reg = new RegExp( /^[0-9]{0,}$/); }else if(rule == 2){ //只能输入字母 var reg = new RegExp( /^[a-zA-Z]{0,}$/); }else if(rule == 0){ //字母或者数字均可 var reg = new RegExp( /^[a-zA-Z0-9][a-zA-Z0-9]{0,}$/); } let result = reg.test(value); if(!result){ this.code = 10010; this.msg = "账号格式错误"; }else{ this.code = 0; this.msg = "验证通过"; } return this.returnMsg(); } //长度验证 public length(value,longArr=[1,6]){ if(longArr[0]<0 || longArr[1]<0){ console.error("区间需为正整数"); return; } if(longArr[0]>longArr[1]){ console.error("左区间端点必须大于右区间端点"); return; } if(value.length>Math.floor(longArr[1])){ this.code = 10010; this.msg = "长度过长"; }else if(value.length<Math.floor(longArr[0])){ this.code = 10010; this.msg = "长度过短"; }else{ this.code = 0; this.msg = "验证通过"; } return this.returnMsg(); } //内容验证 public content(value,forbid=[],reWord=false){ var isMatch = false; var newValue = value; for(let item of forbid){ let reg = new RegExp(item,"igm"); let result = reg.test(value); if(result){ isMatch = true; } if(reWord){ newValue = newValue.replace(reg,reWord); // console.log(newValue) } } // console.log(isMatch) if(isMatch){ this.code = 10010; this.msg = "有违禁词"; this.replaceWord = newValue; }else{ this.code = 0; this.msg = "验证通过"; this.replaceWord = newValue; } return this.returnMsg(); } private returnMsg(){ let verifyMsg = { "code" : this.code, "msg" : this.msg, "content":this.replaceWord } return verifyMsg; } }