The following is the js code (it feels very inelegant when binding objects, I hope an expert can give me some advice!)
function validator(obj,option){//Validation object
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='Input is correct';
self.tag=1;
}else{
self.tip.className='validator_onerror';
self.tip.innerHTML='Sorry, the content you entered does not comply with the rules! ';
self.tag=0;
}
}
validator.prototype.focus=function(){
this.tip.className='validator_onfocus';
this. tip.innerHTML=this.text;
}
function addEvent(el,type,fn){ //Bind event
if(el.attachEvent) {
el['e' type fn ] = fn; //Copy the element reference under IE so that this points to the el object instead of window
el[type fn] = function(){el['e' type fn](window.event);}
el.attachEvent('on' type, el[type fn]);
}else
el.addEventListener(type, fn, false);
}
//Page call method
var inputs=document.getElementsByTagName('input');//The writing here feels weird and not elegant enough, and I haven't found a way to optimize it yet
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(){//Submit form filtering
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;
}
The following is the page demo. It may be missing a small icon. I don’t know how to send executable code.