Home >Web Front-end >JS Tutorial >Teach you step by step how to write a js form validation framework yourself_js object-oriented

Teach you step by step how to write a js form validation framework yourself_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:19:401050browse

In the form program, a lot of Js code is needed on the page to verify the form, whether each field must be filled in, whether
can only be a number, whether ajax is required for remote verification, blablabla.
It would be very cumbersome to write them one by one, so our first goal is to build something similar to a DSL.
Use expressive statements instead of control statements to implement verification.
Secondly, if you write them one by one, there is another problem: all verifications must be passed before they can be submitted. However, individual verification will add a lot of extra control codes because of this feature
, and the verification will often be incomplete. So the second goal is to fully
integrate the entire verification process.
In the end, it cannot be a hard-coded implementation that cannot be expanded. Necessary scalability is still needed.
First, we need a class that can describe field validation

Copy code The code is as follows:

function Field(params){
this.field_id=params.fid; //ID of the field to be validated
this.validators=params.val; //array of validator objects
this. on_suc=params.suc; //The event executed when the verification is successful
this.on_error=params.err; //The event executed when the verification fails
this.checked=false; //Whether it passes Validation
}

We will discuss the validator object later. Next, we extend this class and add the validate method
Copy Code The code is as follows:

Field.prototype.validate=function(){
//Loop through each validator
for(item in this .validators){
//Attach callback events for verification success and verification failure to the validator
this.set_callback(this.validators[item]);
//Execute the Validate method on the validator to verify Whether it complies with the rules
if(!this.validators[item].validate(this.data())){
break; //Stop once any validator fails
}
}
}

Add another method to get the field value:
Copy code The code is as follows:

//Method to get field value
Field.prototype.data=function(){
return document.getElementById(this.field_id).value;
}

The method set_callback to set the validator callback function is as follows:

Copy code The code is as follows:

Field.prototype.set_callback=function(val){
var self=this; //Change a name to store this, otherwise the closure of the function will overwrite this name
val .on_suc=function(){ //Method to verify successful execution
self.checked=true; //Set the field to verify successful execution
self.on_suc(val.tips); //Execute event to verify successful execution
}
val.on_error=function(){ //Method executed when verification fails
self.checked=false; //Field is set to verification failure
self.on_error(val.tips );//Events that fail to perform verification
}
}


Next let’s take a look at the validator. The validator is the class that actually performs the verification process. According to The general verification process can be classified into length verification (including required verification), regular expression verification, custom function verification, and Ajax remote verification, so we define these types A validator class, Ajax remote verification uses jQuery for convenience, other
parts are also useful:



Copy code The code is as follows:

//长度验证的验证器类
function Len_val(min_l,max_l,tip){
this.min_v=min_l;
this.max_v=max_l;
this.tips=tip;
this.on_suc=null;
this.on_error=null;
}
Len_val.prototype.validate=function(fd){
if(fd.lengththis.max_v){
this.on_error();
return false;
}
this.on_suc();
return true;
}
//正则表达式验证器
function Exp_val(expresion,tip){
this.exps=expresion;
this.tips=tip;
this.on_suc=null;
this.on_error=null;
}
Exp_val.prototype.validate=function(fd){
if(!fd){
this.on_suc();
return true;
}
if(this.exps.test(fd)){
this.on_suc();
return true;
}else{
this.on_error();
return false;
}
}
//远程验证器
function Remote_val(url,tip){
this.p_url=url;
this.tips=tip;
this.on_suc=null;
this.on_error=null;
}
Remote_val.prototype.validate=function(fd){
var self=this;
$.post(this.p_url,{f:fd},
function(data){
if(data.rs){
self.on_suc();
return;
}else{
self.on_error();
}
},"json"
);
return false;
}
//自定义函数验证器
function Man_val(tip,func){
this.tips=tip;
this.val_func=func;
this.on_suc=null;
this.on_error=null;
}
Man_val.prototype.validate=function(fd){
if(this.val_func(fd)){
this.on_suc();
}else{
this.on_error();
}
}

最后我们用一个userform的类来做一个入口,在构造的时候传入Field对象的列表,并且将
每一个控件的onblur事件绑定到validate的包装器上

复制代码 代码如下:

function UserForm(items){
this.f_item=items; //把字段验证对象数组复制给属性
for(idx=0;idxvar fc=this.get_check(this.f_item[idx]); //获取封装后的回调事件
$("#" this.f_item[idx].field_id).blur(fc); //绑定到控件上
}
}
//绑定验证事件的处理器,为了避开循环对闭包的影响
UserForm.prototype.get_check=function(v){
return function(){ //返回包装了调用validate方法的事件
v.validate();
}
}

接下来需要定义一个方法来绑定提交按钮的onclick事件:
复制代码 代码如下:

//绑定提交事件到元件
UserForm.prototype.set_submit=function(bid,bind){
var self=this;
$("#" bid).click(
function(){
if(self.validate()){
bind();
}
}
);
}

这里提到了一个UserForm的validate方法,如下:
复制代码 代码如下:

//验证所有的字段
UserForm.prototype.validate=function(){
for(idx in this.f_item){ //循环每一个验证器
this.f_item[idx].validate(); //再检测一遍
if(!this.f_item[idx].checked){
return false; //如果错误就返回失败,阻止提交
}
}
return true; //一个都没错就返回成功执行提交
}


最后用一个例子来看看怎么用:

复制代码 代码如下:




test












要注意的地方就是在循环中使用闭包会茶几,必须用一个方法来代理一下,呵呵


希望对初学js但是还不知道该做点什么怎么做的朋友能有所帮助
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn