Pipevalid.js 2.0 Data validation

Source: Internet
Author: User

Latest Version: 2.0.0
Advantage: Simplify the cumbersome data validation to a simple chained configuration

Small example

Take a look at two small examples and feel the charm of pipevalid

Common validation:

var"da宗熊";var"";if"") {    "名字不能为空"elseif20) {    "名字长度不能超过20"elseif2) {    "名字不能小于2位";}if (error) {    alert(error);}

And after using Pipevalid, you just

varnew PipeValid();valid.check("name")        .notEmpty("名字不能为空")        .max(20"名字长度不能超过20")        .min(2"名字不能小于2位")    .check("text")        .notEmpty("文本不能空")    .check("url")        .url("请正确填写链接""da宗熊""xx""" });if(!result.pass){    alert(result.error);}
Advantage
  1. Reusable chained configuration

    Discard locked if, else operations, use chained definitions, validation errors, where the validation function, is defined once, can be reused.

    valid.check("name").max(10"xx...");
  2. Instances can be reused

    Same instance, same configuration, call different start, return independent result

    // 多个start,使用相同配置,进行多个验证var"da宗熊" });var"da宗熊2" });
  3. Supports asynchronous validation

    Validates the result, returns an object with a simple promise/a specification, supports asynchronous validation

    Valid.check (' name '). Define ( function(val) {        return NewPromise ( function(resolve, Reject) {SetTimeout ( function() {                if(Val.indexof (' bad ') >=0) {reject (); }Else{Resolve (); }            }, +); },' bad ' keyword ' is not included in ' name '); });varresult = Valid.start ({name:' da Zong Xiong '}); Result.always ( function() {    //If the check list contains an async function    //need to be here to get the right results    //Result.pass/result.error/result.key/result.index});
  4. Built-in common validator

    • Notempty: Non-empty
    • Min: Minimum value, accepts two parameters valid.min (int, string);
    • Max: Maximum value, accepts two parameters Valid.max (int, string);
    • URL: Link
    • int: integer
    • Number: Numeric
    • Email: Email
  5. A good development

    Custom chained functions:

    // 定义新的验证函数PipeValid.define("isBear"function(val){return"bear";});// 使用新的链式函数valid.check("bear").notEmpty("bear字段不能为空").isBear("bear必须是bear!");valid.start({ bear:"xx"// ? { pass: false, key: "bear", error: "bear必须是bear!" }

    The new isbear chain function, the 1th parameter, is always a value that needs to be validated.

    Custom validation functions:

    valid.check ( "Min" ). Define (function   (val)  { return  +val >= 3 ; }, ); Valid.start ({min: 1 }); //==> {attr: "min", Error: "Min min is 3"}   
  6. The
  7. Condition verifies that

    Only performs a validation of a requirement (judgment)

    < Span class= "Hljs-comment" >//if the value of the URL is not empty, verify that it is linked; empty, then do nothing.  Valid.check ( "url" ). Notempty (). then (). URL ( "input must be a link" ). End (); Valid.start ({url: " "}"; //? {Pass:true}  Valid.start ({url:  "XXYY" }); //? {pass:false, key: "url", Error: "Input must be a link"}   
    After the

    has used then, the previously added function is converted to the pre-validation condition, and end is the end of the then function.

    If this check operation has no subsequent validation, the End function can be ignored.

  8. Support for property expressions

    If you want to verify an expression like "Data.code" or "list[1].name", Pipevalid can help you.

    varnew PipeValid();valid.check(‘data.code‘)    .int(‘code必须是整型‘);var result = valid.start({    ‘789d‘false;
Apipipevalid

1. Check (name:string| Object)
Returns an Item instance that has all of the validation methods defined

varnew PipeValid();var checker = pipe.check(‘name‘);checker.min(3‘名字最短3位‘);

If the argument is an object, the method is called rule

Name if it is a string, it supports the notation of an attribute expression:

pipe.check(‘data.code‘// 检测 data 的 code 属性pipe.check(‘list[].name‘// 检测 list 列表中,所有子项的 name 属性pipe.check(‘list[0].name‘// 检测 列表 的第 1 位子项的 name 属性pipe.check(‘[].name‘// 检测该列表的所有 name 属性

Therefore, the attribute name must not contain "[]." Oh ~.

2. Rule (Checklist:object)
Configure the validator in array form

pipe.rule({    // 多个验证规则,同时也支持 then 和 end 方法  name: [    [‘notEmpty‘‘不能为空‘],    [‘min‘3‘最少3位‘]  ],    // 单个验证规则  age: [‘int‘‘必须是整数‘]});

The rules are configured in the following form:

String|Function, 验证参数1.String|Object]

There can be multiple validation parameters, but the number is strictly equal to the number of parameters of the validation function minus one

3, define (name:string, fn:function)
Checkernew validation methods are being added

PipeValid.define(‘isBear‘function(value){  return‘bear‘;});checker.isBear(‘必须是bear!‘);

Pipevalid.define is equivalent to Pipe.define, but only after Pipe.define, continue to return this object

4. Start (Data:object, Restrict:array, Ischeckall:boolean?)

  • Data is the object that needs to be validated.
  • Restrict is the rule, this validation, which checker to use, the string array oh
  • Ischeckall, does this verify that all errors are returned? The result.error will be an array

    The method, which always returns a Thenable object, has a Then/always/catch method.
    If all checker are executed, there is no asynchronous detection, and the result will be a synchronous return.
    If there is an asynchronous detection, the result is also returned asynchronously.

    varnew PipeValid();// 假设 noneBadword 是异步验证pipe.check(‘name‘).min(3‘名字最短3个字‘).noneBadword(‘不能含有非法关键字‘);var‘da宗熊‘// undefined,因为需要等待 noneBadword 的执行result.always(function() {// 得到最终的结果});

    Attention:

    If check (' name ') is defined, but in start ({age:1}) and does not contain the name attribute, the detection of the Name property is ignored.

    If it is necessary to verify, specify the Restrict list, start ({age:1}, [' Name ', ' age '), have a restrict list, then only validate the contents specified by the list, and if the found content does not exist, it will also throw a set error.

Pipevalid.item

When the Pipevalid instance calls the check (String) method, an Item object is returned

1. Built-in verification

    • Max (Len:int, error:string| Object)
    • Min (Len:int, error:string| Object)
    • URL (error:string| Object)
    • Int (error:string| Object)
    • Email (error:string| Object)
    • Notempty (error:string| Object)

All Item instances have all of the above validation methods by default

2, define (fn:function, Parameter 2?, Parameter 3?, Error:string| Object)
Custom error validation, which verifies that the 1th parameter of the function FN must be a value to validate

pipe.check(‘word‘)    .define(function(val, parm1, params) {        // 返回 true -> 验证通过        // 返回 false -> 验证不通过        // 返回 promise 对象,如果是 reject 不通过,resolve 则通过        // promise对象的 reject 如果附带参数,则会把 error 覆盖掉!!!    ‘param1‘‘param2‘‘error text‘);

Where, if the custom function, only val a parameter, then corresponding, "Parameter 2?, Parameter 3?" should not exist

3, then () and end ()
Then, all the methods in the front chain are changed to validate the condition.
End, close the then operation

// 如果当前的值,不为空,才去验证 url 是否链接pipe.check(‘url‘).notEmpty()    .then()    .url(‘必须是链接‘);// 如果 text 大于20,则验证是否连接,否则判定 text 是否整数pipe.check(‘text‘)    .min(20)    .then()    .url(‘text必须是链接‘)    .end()    .int(‘请输入整数‘);

4. Check (name:string)
Call Father's Check method

5, Custom (Fn:function (Val, next:function))
Fully customizable validation, the this context in FN, is changed to an object that has all of the current validators.

/* Max Verify that it is defined as follows: Max:    Function (val, len) {val = "" + val;  Return Val && val.length <= Len; }*/ Pipe.check (). Custom (function   { //sentenced The current Val length is less than or equal to ten  if  (this . Max (10 )) {//perform validation of integers  if  (! This . Int ()) {//thrown out error  next (//no error, notification continues to execute  next (); });

In the custom function, all validators for this method invocation are bound by the Val parameter by default.
If an error is set in the validation function of this, then, when the validation error occurs, the execution of the function is immediately interrupted and an error is thrown.
However, if it is an asynchronous validation function, it needs to be interrupted when reject occurs, so be careful with the async function.

The above code is equivalent to

pipe.check(‘name‘)    .custom(function(val, next) {        // 判定当前 val 长度小于等于10        if (this.max(10)) {            // 执行是否整数的验证,如果不是整型,则抛出错误            this.int(‘输入必须是整数‘);        }        // 没有错误,通知继续执行        next();    });
Pipevalid.thenable

An imitation Promise object that provides only the Reject/resolve/then/always/catch method

varnew Thenable();thenable.resolve(1);thenable.then(function(data) {    // 1}).then(function(data) {    // undefined    return {};}).then(function(data) {    // {}});
Contact

Have bug,or interest, can contact, Penguin mailbox: [email protected]

Pipevalid.js 2.0 Data validation

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.