Data Validation "Web front end, forms"

Source: Internet
Author: User

Data validation

Recently done backstage more, road seven or eight bad data verification, get tired. So, get a form to verify the stuff out, to achieve quick, brief, and not annoying validation.

Here's a look at the data validation in several ways, what's different. First there is the data that needs to be validated:

<form>    <input type="text" name="name" />    <input type="text" name="password" />    <input type="number" name="Age" />    <input type= "checkbox" name= "sex" value=" 0 " />Man<input type="checkbox" name="Sex" value ="1" />Woman<input type="text" name="Address" />    <input type="text" name="Phone" />    <input type="text" name="qq" />    <input type="text" name="email" />    <input type="text" name="homepage" /></form>

At first glance, Lin Lin, there are 9 data that need to be verified:

    1. Name: Non-null, minimum 3 bits, maximum 10 bits
    2. Password: non-null, minimum 6, maximum 20 bits
    3. Age: Non-empty, integer
    4. Sex: Non-empty
    5. Address: Non-empty, maximum 50 bits
    6. Phone: Available, phone number
    7. QQ: Can be empty
    8. Email: Available, email
    9. Homepage: nullable, Link
Traditional

Get this pile of data, that there is nothing to say, one by one if/else judge it:

if"" ){    return"name不能空";}elseif3){    return"name不小于3";}elseif10 ){    return"name不大于10";}........每个条件一端判定

As you can see, if you add another decision, you need a new if, a new return. If only one or two data is OK, but the data more than one, simply can not see.

Moreover, the form of data, there will generally be new and modified two parts, and their data validation, is often the majority of the same, a small number of different. OMG, but also to the dense judgment of a copy, almost a two-part ...

It's just a dehumanizing disaster ......... ..........

Policy mode

Because the same property, its validation is consistent, so we can get a copy of the policy configuration:

varobj = {Name: function(val){        if(val = =""){return "Name cannot be empty"; }Else if(Val.length <3){return "name is not less than 3"; }Else if(Val.length >Ten){return "name is not much more than ten"; }}, Password: function(val){        if(val = =""){return "Password cannot be empty"; }Else if(Val.length <6){return "Password not less than 6 bits"; }Else if(Val.length > -){return "Password not greater than 20 bits"; }    }    ...    ...}

Hard, write a configuration, and then, when verifying, only need to provide the data to be verified, loop execution, then OK:

f Unction  valid   (data)  { for  (var  i in  data) {var  item = data[i], fn = obj[i];        //gets the policy configured in obj  if  (FN) {//function in execution policy  var  res = Fn[item]            ;            //if there is a return, the error is generated  if  (RES)            {return  res; }}} //safe execution here  return  true ;}  

The strategy is good, the method of invoking the tool is also good, the rest is to use:

var res = valid({    "名字",    "密码...",    ...    ...});iftrue ){    alert("验证通过");}else{    alert("验证错误:" + res);}

We have done a definition verification method and reuse. At first glance, there is no problem. Feel the verification code, go to the pinnacle of the code world, impeccable, have wood?

But a closer look, in some places, is still unsatisfactory. If, add a field now, blog home: blogpage, link.
Quite simply, in obj, add a policy that validates the link.

However, we have not already had the homepage strategy, also has the link validation? Don't you repeat the two pieces?
A child with obsessive-compulsive disorder must have extracted the link validation code into a separate function for both sides to invoke.

But with the interface of public authentication code, more and more? OMG, a dense public authentication code, is another disaster ...

Or, is there a new form with different data? Define a policy object again?

Configuring policies

If we take the policy pattern, we can go against it, put the validated code into the policy object, give the data to be validated, and configure the validation strategy.

Code I am lazy, do not wash the writing:

varobj = {notempty: function(){...}, Max: function(){...}, min: function(){...}, URL: function(){...}, email: function(){...}, QQ: function(){...}, Number: function(){...},    ...    ...}

Define an object that validates the required functions for the data, and then, for each data, specify the interface to validate:

var checkObj = {    name: ["notEmpty|不能空""max|10|最大10""min|3|最小3"],    password: ["notEmpty|不能空""max|20|最大10""min|6|最小6"],    ...    ...}

Use on, also very simple, from Checkobj, find the Authentication interface KEY, and then through Obj[key] find the real validation function, to verify.
As for how to realize, here is hehe ...

A simple verification, divided into 3 layers, almost like MVC ah, there are wood ah?
But, quite appreciate this one way, completely for that kind of intolerable patient that cannot tolerate repetitive code, tailor-made, have?

Pipevalid.js

Pipevalid.js, a tool library of data validation is written according to the pattern of configuration policy. Among them, there is this very powerful chain expression syntax, built-in common numbers, integers, non-null, URL, email, minimum, maximum authentication, support to expand the underlying authentication interface, or non-interface authentication.

Make a chestnut:

varvalid = Pipevalid ();//support for non-new mode generation, you can also add new//Configure a series of validation actionsValid.check ("Name"). Notempty (). Error ("Name cannot be empty"). Max ( the). Error ("The name is not more than 15 words."). Min (3). Error ("Minimum 3-bit name");//The smart notation for error messages, the last one to verify the function, is the error messageValid.check ("Password"). Notempty ("Password cannot be empty"). Max ( -,"password max."). Min (6,"Password min. 6");//Call start to start validationHow much data is passed, and how much is verified//Start returns the Deferred objectValid.start ({name:"xxxx", Password:"YYYYY",    ...    ...}). Done function(){    //Validate all through}). Error ( function(err){Console.log (ERR);//Err = {attr: "Verified property name", Error: "Message"}}). Always ( function(){    whether success or failure, always feel that there is no use here ...    //After version kill it});

In the check, the configuration of the data validation, start, is only performed for the actual validation of the processing. Also, support for expanding your own validation:

valid.add("isBear"function(val){    return"da宗熊";});// 使用valid.check("bear").isBear("竟然不是da宗熊!!不通过");

Notice the isbear followed by check ()? After the Add function, Isbear can be very intelligent to identify the first parameter, is the error processing information.

Built-in powerful then/end features. To verify: the homepage field, which can be empty, is not empty, must be a link:

// 如果 homePage 不是空的时候,进行是否链接的验证valid.check("homePage").notEmpty().then().url("homePage必须是链接").end();

Then be sure to have end as the end.

Or, we are very willful, want to customize the function, to verify, Pipevalid also satisfies your request:

// define 的第一个参数,是函数,改函数,只支持1个参数!!!// 验证 xxx 字段,是否等于 xxxvalid.check("xxx").define(function(val){    return"xxx";  // 一定要返回 Boolean 值"这是xxx有错了");

Public Authentication Data Management:

// 它有公共数据管理的对象,不用每次 start 都把所有数据传入// 把不更改的数据,传入 data 中,能节省每次 start 传入的数据// 当然,相同名字时,start 的 优先于 data 的valid.data({    "xxx",    11,    ...    ...});
At last

Well, summing up, using pipevalid.js, really very loaded force. Feel the whole person's force lattice is high, have wood? v 1.0.0 version, 3.7K ah?

It means simple, one or two data validation, really don't want to use this thing. But the data is too long ... Brother, give me 10 copies of pipevalid~.

Fill in the link:

Github:https://github.com/linfenpan/flamingo/tree/master/learn/valid

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Data Validation "Web front end, forms"

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.