How to Write a js form verification framework by yourself _ js object-oriented

Source: Internet
Author: User
In fact, I can simply use js myself, but as many beginners know more about KnowHow, I am so brave enough to record some of the gains, so that more beginners can know the implementation process of one thing, saving the process of exploring in the source code. In the form program, a lot of Js code is required on the page to verify the form. Is each field required?
It can only be a number. Do you need ajax to perform remote verification? blablabla.
If we write data separately, it is very complicated. Therefore, our first goal is to build something similar to DSL,
The statement is used for verification instead of the control statement.
Second, if you write data separately, you must verify all the data before submitting the data.
This feature adds a lot of additional control code and is often not fully verified. Therefore, the second goal is to be comprehensive.
Integration of the entire verification process.
In the end, it cannot be a write-down implementation that cannot be expanded. The necessary scalability is still required.
First, we need a class that can describe field verification.

The Code is as follows:


Function Field (params ){
This. field_id = params. fid; // ID of the field to be verified
This. validators = params. val; // an array of validators.
This. on_suc = params. suc; // The Event executed when the verification is successful.
This. on_error = params. err; // event executed when verification fails
This. checked = false; // whether the verification is successful
}


We will discuss about the validators object later. Next we will extend this class and add the validate method.

The Code is as follows:


Field. prototype. validate = function (){
// Loop every validator
For (item in this. validators ){
// Attaches a callback event for the validators for verification success and verification failure.
This. set_callback (this. validators [item]);
// Execute the Validate method on the validators to verify that they comply with the rules
If (! This. validators [item]. validate (this. data ())){
Break; // It is stopped once any validator fails.
}
}
}


Add another method to obtain the field value:

The Code is as follows:


// Method for obtaining the field value
Field. prototype. data = function (){
Return document. getElementById (this. field_id). value;
}


Set_callback:

The Code is as follows:


Field. prototype. set_callback = function (val ){
Var self = this; // store this by another name. Otherwise, the closure of the function will overwrite this name.
Val. on_suc = function () {// Method for verifying successful execution
Self. checked = true; // set the field to successful verification.
Self. on_suc (val. tips); // events with successful verification execution
}
Val. on_error = function () {// method executed when verification fails
Self. checked = false; // The field is set to Verification Failed.
Self. on_error (val. tips); // events that fail Verification
}
}



Next let's take a look at the validators. The validators are classes that actually execute the verification process. According to the general verification process, we
It can be categorized into, length verification (including mandatory verification), regular expression verification, custom function verification, Ajax far
So we define these types of validators, Ajax remote verification to facilitate reference of jQuery, Other
Some of them are also useful:

The Code is as follows:


// Length verification validator class
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. length This. max_v ){
This. on_error ();
Return false;
}
This. on_suc ();
Return true;
}
// Regular Expression validators
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;
}
}
// Remote validators
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;
}
// User-Defined Function validators
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 ();
}
}


Finally, we use a userform class as an entry. During construction, we pass in the Field Object List and
The onblur event of each control is bound to the validate package.

The Code is as follows:


Function UserForm (items ){
This. f_item = items; // copy the field validation object array to the attribute
For (idx = 0; idx Var fc = this. get_check (this. f_item [idx]); // obtain the encapsulated callback event
$ ("#" + This. f_item [idx]. field_id). blur (fc); // bind to the control
}
}
// The processor bound to the verification event. To avoid the impact of loops on the closure
UserForm. prototype. get_check = function (v ){
Return function () {// return events that wrap the validate Method
V. validate ();
}
}


Next, you need to define a method to bind the onclick event of the submit button:

The Code is as follows:


// Bind the submission event to the component
UserForm. prototype. set_submit = function (bid, bind ){
Var self = this;
$ ("#" + Bid). click (
Function (){
If (self. validate ()){
Bind ();
}
}
);
}


Here we mention the validate method of a UserForm, as follows:

The Code is as follows:


// Verify all fields
UserForm. prototype. validate = function (){
For (idx in this. f_item) {// loop each validator
This. f_item [idx]. validate (); // check again
If (! This. f_item [idx]. checked ){
Return false; // if an error occurs, an error is returned to prevent submission.
}
}
Return true; // if none of them are correct, a successful execution submission is returned.
}



Finally, let's use an example to see how to use it:

The Code is as follows:





Test

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.