当前位置:Gxlcms > JavaScript > validator验证控件使用代码_表单特效

validator验证控件使用代码_表单特效

时间:2021-07-01 10:21:17 帮助过:16人阅读

下面是js代码(在绑定对象的时候感觉很不优雅,希望高人能指点一二啊!)
代码如下:

function validator(obj,option){//验证对象
var self = this;
if(!(self instanceof validator))
return new validator(obj,option);
self.source={'mobile':'^(13|14|15|18)[0-9]{9}$','postcode':'^\\d{6}$','integer':'^-?\\d*$','email':'^\\w+((-\\w+)|(\\.\\w+))*\\@[A-Za-z0-9]+((\\.|-)[A-Za-z0-9]+)*\\.[A-Za-z0-9]+$','url':'^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$'};
for(var i in self.source){
if(i==option.type)
self.type=self.source[i];
}
self.tag=2;
self.input=obj;
self.options=option;
self.tip=document.getElementById(self.options.tips);
self.text=self.tip.innerHTML;
self.init(obj);
}
validator.prototype.init=function(o){
var self=this;
addEvent(o,'focus',function(){
self.focus();
});
addEvent(o,'blur',function(){
self.valid();
});
}
validator.prototype.valid=function(){
var self=this;
var reg=self.options.reg||self.type;
if(new RegExp(reg).test(self.input.value.replace(/\s/ig,''))){
self.tip.className='validator_oncorrect';
self.tip.innerHTML='输入正确';
self.tag=1;
}else{
self.tip.className='validator_onerror';
self.tip.innerHTML='对不起,您输入的内容不符合规则!';
self.tag=0;
}
}
validator.prototype.focus=function(){
this.tip.className='validator_onfocus';
this.tip.innerHTML=this.text;
}
function addEvent(el,type,fn){ //绑定事件
if(el.attachEvent) {
el['e'+type+fn] = fn; //IE下拷贝元素引用,使this指向el对象而不是window
el[type+fn] = function(){el['e'+type+fn](window.event);}
el.attachEvent('on'+type, el[type+fn]);
}else
el.addEventListener(type, fn, false);
}
//页面调用方法
var inputs=document.getElementsByTagName('input');//这里的写法感觉怪怪的,不够优雅,暂时也没找到优化的办法
var arr=[];
arr[0]=validator(inputs[0],{type:'postcode',tips:'m1'});
arr[1]=validator(inputs[1],{type:'url',tips:'m2'});
arr[2]=validator(inputs[2],{type:'email',tips:'m3'});
arr[3]=validator(inputs[3],{type:'mobile',tips:'m4'});
arr[4]=validator(inputs[4],{type:'integer',tips:'m5',reg:'^-?\\d*$'});
function submitForm(){//提交表单过滤
var l=arr.length;
for(var i in arr){
if(arr[i].tag==1)
l--;
else if(arr[i].tag==2){
arr[i].valid();
}
}
if(l!=0)return false;
}

以下是页面demo,可能缺少一个小图标,汗,不知道怎么发可执行的代码。
代码如下:









验证控件



验证控件