GVKun编程网logo

async-validator 说明文档(async怎么实现的)

19

关于async-validator说明文档和async怎么实现的的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于angular–AsyncValidatorThrowExpectedval

关于async-validator 说明文档async怎么实现的的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于angular – Async Validator Throw Expected validator返回Promise或Observable、angularjs – 等待$asyncValidators提交表单、Angular:我无法使用 *ngIf 在 UI 中显示 Asyn Validators 的错误、ASP.NET CompareValidator validate Currency等相关知识的信息别忘了在本站进行查找喔。

本文目录一览:

async-validator 说明文档(async怎么实现的)

async-validator 说明文档(async怎么实现的)

异步验证
验证表单异步。https://github.com/freeformsystems/async-validate的变体

NPM版本 建立状态 测试范围 gemnasium deps 节点版本 npm下载

API
以下是从早期版本的async-validate中修改的。

用法
基本用法包括定义描述符,将其分配给模式,并将要验证的对象和回调函数传递给validate模式的方法:

var schema = require(''async-validator'');
var descriptor = {
  name: {
    type: "string",
    required: true,
    validator: (rule, value) => value === ''muji'',
  },
};
var validator = new schema(descriptor);
validator.validate({name: "muji"}, (errors, fields) => {
  if(errors) {{name : “ muji ” },(errors,fields)=> {
   if(errors){
     //验证失败,错误是所有错误的数组
    //字段是由字段名称键入的对象,数组为
    /每个字段的/ errors 
    return handleErrors(errors, fields);
  }
  //验证通过
});

// PROMISE USAGE 
validator.validate({
  name: "muji",
  asyncValidator: (rule, value) => axios.post(''/nameValidator'', { name: value }),
}, (errors, fields) => {
  if(errors) {
     //验证失败,错误是所有错误的数组
    //字段是由字段名称键入的对象,
    每个字段返回//错误
     return handleErrors(errors, fields);
  }
  //验证通过
})
  .then(() => {
     //验证通过
  })
  。catch(({errors,fields})=> {
     return  handleErrors(errors,fields);
  })
Validate
function(source,[ options ],callback):Promise
source:要验证的对象(必需)。
options:描述验证处理选项的对象(可选)。
callback:验证完成时调用的回调函数(必需)。
该方法将返回一个Promise对象,如:

then(),验证通过
catch({ errors, fields }),验证失败,错误是所有错误的数组,字段是由字段名称键入的对象,其数组为
Options
first:Boolean,callback当第一个验证规则生成错误时调用,不再处理验证规则。如果您的验证涉及多个异步调用(例如,数据库查询),并且您只需要第一个错误,请使用此选项。

firstFields:Boolean | String [],callback当指定字段的第一个验证规则生成错误时调用,不再处理相同字段的验证规则。 true意味着所有领域。

Rules
规则可以是执行验证的函数。

function(rule, value, callback, source, options)
rule:源描述符中与要验证的字段名称对应的验证规则。始终为其分配一个field属性,其中包含要验证的字段的名称。
value:要验证的源对象属性的值。
callback:完成验证后调用的回调函数。它期望传递一组Error实例来指示验证失败。如果检查是同步的,您可以直接返回false或Error或Error Array。
source:传递给validate方法的源对象。
options: 其他选项。
options.messages:包含验证错误消息的对象将与defaultMessages深度合并。
传递给validate或asyncValidate传递给验证函数的选项,以便您可以在验证函数中引用瞬态数据(例如模型引用)。但是,保留了一些选项名称; 如果使用选项对象的这些属性,则会覆盖它们。保留的属性是messages,exception和error。

var schema = require(''async-validator'');
var descriptor = {
  name(rule, value, callback, source, options) {
    var errors = [];
    if(!/^[a-z0-9]+$/.test(value)) {
      errors.push(
        new Error(
          util.format("%s must be lowercase alphanumeric characters",
            rule.field)));
    }
    return errors;
  }
}
var validator =  new  schema(descriptor);
validator.validate({name : “ Firstname ” },(errors,fields)=> {
   if(errors){
     return  handleErrors(errors,fields);
  }
  //验证通过 
});
针对单个字段测试多个验证规则通常很有用,这样做可以使规则成为对象数组,例如:

var descriptor = {
  email: [
    {type: "string", required: true, pattern: schema.pattern.email},
    {validator(rule, value, callback, source, options) {
       var errors = [];
      //如果电子邮件地址已经存在于数据库测试
      //并添加验证错误,如果它的错误阵列
      return errors;
    }}
  ]
}
Type
指示type要使用的验证器。已识别的类型值为:

string:必须是类型string。This is the default type.
number:必须是类型number。
boolean:必须是类型boolean。
method:必须是类型function。
regexp:必须是RegExp创建新项时不生成异常的实例或字符串RegExp。
integer:必须是类型number和整数。
float:必须是类型number和浮点数。
array:必须是由...确定的数组Array.isArray。
object:必须是类型object而不是Array.isArray。
enum:价值必须存在于enum。
date:值必须有效,由确定 Date
url:必须是类型url。
hex:必须是类型hex。
email:必须是类型email。
Required
该required规则属性表示该字段必须存在于源对象被验证。

Pattern
该pattern规则属性指示一个正则表达式的值必须匹配,才能通过验证。

Range
使用min和max属性定义范围。对于string和array类型进行比较length,对于number类型,数量不得小于min或大于max。

Enumerable
要验证字段的确切长度,请指定该len属性。对于属性执行string和array类型比较length,对于number类型,此属性指示完全匹配number,即,它可能仅严格等于len。

如果len属性与min和max范围属性组合,len则优先。

枚举
要从可能值列表中验证值,请使用enum带有enum列出该字段有效值的属性的类型,例如:

var descriptor = {
   role: {type: "enum", enum: [''admin'', ''user'', ''guest'']}
}
Whitespace
通常将仅包含空格的必填字段视为错误。要为仅包含空格的字符串添加其他测试,请将whitespace属性添加到值为的规则true。规则必须是一种string类型。

您可能希望清理用户输入而不是测试空格,请参阅transform以获取允许您去除空格的示例。

Deep Rules

如果您需要验证深对象属性可能对于那些的验证规则这样做object或者array通过向指定嵌套规则类型fields规则的属性。

var descriptor = {
  addres: {
    type : “ object ”,requried: true,
    fieds: {
      street : {type : “ string ”,required : true },
      city : {type : “ string ”,required : true },
      zip : {type : “ string ”,required : true,len :8,message : “ invalid zip ” }
    }
  },
  name : {type : “ string ”,required : true }
}
var validator =  new  schema(descriptor);
validator.validate({address : {}},(errors,fields)=> {
   // address.street,address.city,address.zip的错误 
});
请注意,如果未required在父规则上指定属性,则对于不在源对象上声明的字段完全有效,并且不会执行深度验证规则,因为没有任何要验证的内容。

深度规则验证为嵌套规则创建架构,因此您还可以指定options传递给schema.validate()方法。

var descriptor = {
  address: {
    type: "object", required: true, options: {single: true, first: true},
    fields: {
      street: {type: "string", required: true},
      city: {type: "string", required: true},
      zip: {type: "string", required: true, len: 8, message: "invalid zip"}
    }
  },
  name: {type: "string", required: true}
}
var validator = new schema(descriptor);

validator.validate({ address: {} })
  .catch(({ errors, fields }) => {
     //现在只有街道和名称的错误     
  });
父规则也经过验证,因此如果您有一组规则,例如:

var descriptor = {
  roles: {
    type: "array", required: true, len: 3,
    fields: {
      0: {type: "string", required: true},
      1: {type: "string", required: true},
      2: {type: "string", required: true}
    }
  }
}
然后提供一个源对象,{roles: ["admin", "user"]}然后创建两个错误。一个用于数组长度不匹配,另一个用于索引2处缺少的所需数组条目。

defaultField
该defaultField属性可与arrayor或objecttype 一起使用,以验证容器的所有值。它可能是一个object或array包含验证规则。例如:

var descriptor = {
  urls: {
    type: "array", required: true,
    defaultField: {type: "url"}
  }
}
请注意,defaultField扩展为fields,请参阅深层规则。

Transform 转变
有时需要在验证之前转换值,可能是为了强制价值或以某种方式对其进行消毒。为此,请transform向验证规则添加一个函数。该属性在验证之前进行转换,并重新分配给源对象,以便在适当的位置改变属性的值。

var schema = require(''async-validator'');
var sanitize = require(''validator'').sanitize;
var descriptor = {
  name: {
    type: "string",
    required: true, pattern: /^[a-z]+$/,
    transform(value) {
      return sanitize(value).trim();
    }
  }
}
var validator = new schema(descriptor);
var source = {name: " user  "};
validator.validate(source)
  .then(() => assert.equal(source.name, "user"));;
如果没有transform函数验证,则由于模式不匹配而失败,因为输入包含前导和尾随空格,但是通过添加转换函数验证过程并且字段值同时被清理。

Messages
根据您的应用程序要求,您可能需要i18​​n支持,或者您可能更喜欢不同的验证错误消息。

实现此目的的最简单方法是为message规则分配:

{name : {type : “ string ”,required : true,message : “ Name is required ” }}
消息可以是任何类型,例如jsx格式。

{name : {type : “ string ”,required : true,message : < b >姓名是必需的< / b > }}
消息也可以是一个函数,例如,如果你使用vue-i18n:

{name : {type : “ string ”,required : true,message :()=>  this。$ t(''名称是必需的'')}}
您可能需要针对不同语言使用相同的架构验证规则,在这种情况下,复制每种语言的架构规则是没有意义的。

在这种情况下,您只需提供自己的语言消息并将其分配给架构:

var schema = require(''async-validator'');
var cn = {
  required: ''%s 必填'',
};
var descriptor = {name:{type: "string", required: true}};
var validator = new schema(descriptor);
// deep merge with defaultMessages
validator.messages(cn);

如果要定义自己的验证函数,最好将消息字符串分配给消息对象,然后通过options.messages验证函数中的属性访问消息。

asyncValidator
您可以为指定字段自定义异步验证功能:

const fields = {
  asyncField:{
    asyncValidator(rule,value,callback){
      ajax({
        url:''xx'',
        value:value
      }).then(function(data){
        callback();
      },function(error){
        callback(new Error(error))
      });
    }
  },

  promiseField:{
    asyncValidator(rule, value){
      return ajax({
        url:''xx'',
        value:value
      });
    }
  }
};
validator
您可以自定义验证指定字段的功能:

const fields = {
  field:{
    validator(rule,value,callback){
      return value === ''test'';
    },
    message: ''Value is not equal to "test".'',
  },

  field2:{
    validator(rule,value,callback){
      return new Error(`''${value} is not equal to "test".''`);
    },
  },
 
  arrField:{
    validator(rule, value){
      return [
        new Error(''Message 1''),
        new Error(''Message 2''),
      ];
    }
  },
};
常问问题
如何避免警告
var Schema = require(''async-validator'');
Schema.warning = function(){};
测试用例
npm test
npm run chrome-test
覆盖
npm run coverage
公开报道/目录

执照
一切都是麻省理工学院。

angular – Async Validator Throw Expected validator返回Promise或Observable

angular – Async Validator Throw Expected validator返回Promise或Observable

我试图用密码值确认密码.我按照Async验证器标准完成了.但我想知道它没有工作,并给我以下错误.请告诉任何人如何解决此错误.

Expected validator to return Promise or Observable.

这是我的代码.

呼叫验证器:

cPass: ['',Validators.compose([
  Validators.required,Validators.maxLength(32),Validators.minLength(10)
]),this.validPassword.bind(this)
]

自定义验证功能:

validPassword(control: AbstractControl) {            
  const isEqual = Observable.of(this.password == control.value);
  return isEqual ? { valid : true } : null;         
}
这个错误说明了一切:

Expected validator to return Promise or Observable.

你在函数中返回对象| null.

只需将其更改为:

validPassword(control: AbstractControl) {
  return observableOf('12345678910' === control.value).pipe(
    map(result => result ? { invalid: true } : null)
  );
}

STABKBLITZ DEMO

angularjs – 等待$asyncValidators提交表单

angularjs – 等待$asyncValidators提交表单

我有一个具有用户名字段和其他字段的表单,此字段有一个异步验证器,用于在您尝试提交表单时检查该用户名是否可用(表单上的其他字段使用异步验证).我使用此指令验证并提交表单(仅当它有效时):

<form validation-submit="submit()"></form>
app.directive('validationSubmit',['$parse',function($parse) {
    return {
        restrict: 'A',require: '?form',compile: function($element,attr) {
            var submitFn = $parse(attr.validationSubmit);

            return function link(scope,element,attrs,FormController) {
                var submit = function(event) {
                    scope.$apply(function() {
                        if (! FormController.$valid) {
                            return;
                        }

                        submitFn(scope,{$event: event}));
                    });
                };

                element.bind('submit',submit);

                scope.$on('$destroy',function() {
                    return element.off('submit',submit);
                });
            }
        }
    };
}]);

问题是该指令不等待挂起的异步验证完成.如何将此指令更改为仅在完成并传递所有异步验证后提交?

解决方法

最近我创建了一些指令,检查电子邮件或电话号码是否可用.我找到了帮助我的解决方案.这是 $asyncValidators.

app.directive('validationSubmit',link: function(scope,FormController) {
                /**
                *returns promise
                **/
                FormController.$asyncValidators.validEmail = function (modelValue) {
                    return $q(function (resolve,reject) { 
                    //Here you should make query to your server and find out wether username valid or not
                    //For example it Could be:
                    $http('http://your_api_server/Available').then(function (response) {
                            if (response.data.Available) {
                                resolve();
                            } else {
                                reject();
                            }
                        },function (err) {
                            reject(err.data);
                        });  
                        });
                };
            }

    };
}]);

您应该向表单添加属性名称:

<form validation-submit="submit()" name="myForm"></form>

现在您有机会在控制器中检查表单的系统属性:

$scope.submit = function(){
    //Here will be your logic
    if($scope.myForm.$valid ||
       $scope.myForm.$invalid || 
       $scope.myForm.$pending ||
       $scope.myForm.$submitted){
          //do whatever you want
        }
}

Angular:我无法使用 *ngIf 在 UI 中显示 Asyn Validators 的错误

Angular:我无法使用 *ngIf 在 UI 中显示 Asyn Validators 的错误

我不知道为什么您的自定义验证器不起作用,您应该将其添加到您的问题中。对于这种想法,您实际上并不需要自定义验证器。您可以只比较 FormControls 之间的值。这是一个关于如何在 html 文件中访问 FormControl 的示例。

在您的打字稿文件中:

export class myComponent implements OnInit {

  public password: FormControl = new FormControl('',[Validators.required]);
  public passwordConfirmation: FormControl = new FormControl('',[Validators.required]);
  public fg: FormGroup;

  public constructor() { }

  public ngOnInit(): void {
    this.fg = new FormGroup({
      email: this.password,emailConfirmation: this.passwordConfirmation
    });
  }

}

在您的 HTML 文件中:

<div>
  <label for="password" [ngClass]="{'text-danger': !password.valid && password.touched}">Password:</label>
  <input id="password"type="password" [ngClass]="{'is-invalid': !password.valid && password.touched}" formControlName="password">
  <small *ngIf="!password.valid && password.touched">Password required</small>
</div>
<div>
  <label for="password-confirmation" [ngClass]="{'text-danger': !passwordConfirmation.valid && passwordConfirmation.touched}">Password confirmation:</label>
  <input id="password-confirmation"type="text" [ngClass]="{'is-invalid': !passwordConfirmation.valid && passwordConfirmation.touched}" formControlName="passwordConfirmation">
  <small *ngIf="(password.value !== passwordConfirmation.value) && passwordConfirmation.touched">Password does not match</small>
</div>

ASP.NET CompareValidator validate Currency

ASP.NET CompareValidator validate Currency

CompareValidator HAS BUG OR I AM MISING SOMETHING ? 

I have a text Box for price then I have a compare validator. The problem here is that even if I put a number like $32000.00 it gives me the error message

I have a CompareValidator, I set the Operator=DataTypeCheck, and Type=Currency
However, on the application, if i enter $3,000.00 triggers the error message

 

<asp:CompareValidator ID="CompareValidator6" ControlTovalidate="txtPrice" Operator="DataTypeCheck" Type="Currency" runat="server" ErrorMessage="Currency Format Only Accepted For Price"></asp:CompareValidator>

<asp:CompareValidator ID="CompareValidator_txtAmount" runat="server" display="Dynamic" ErrorMessage="Amount is invalid" ControlTovalidate="txtAmount" Operator="DataTypeCheck"  Type="Currency" CultureInvariantValues="True"></asp:CompareValidator>

 

Does anyone encounter problem using the compare validator against a textBox with operator=DataTypeCheck, type="Currency" and the textBox value contains more than 2 decimal point?
With type="Double" it works fine with more than 2 decimal point but must not have comma.
Below is my test result:
Currency 10,200.20 pass
Currency 10,200.204 fail
Double 10,200.20 fail
Double 10200.204 pass
Any suggestion to overcome this issue?

 

http://www.cnblogs.com/emanlee/archive/2009/08/12/1544645.html

http://forums.asp.net/t/1277960.aspx

http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.faqs/2004-08/0089.html

http://www.vbdotnetforums.com/web-forms/16645-comparevalidator-currency.html

http://www.codeguru.com/forum/showthread.php?t=307614

今天关于async-validator 说明文档async怎么实现的的介绍到此结束,谢谢您的阅读,有关angular – Async Validator Throw Expected validator返回Promise或Observable、angularjs – 等待$asyncValidators提交表单、Angular:我无法使用 *ngIf 在 UI 中显示 Asyn Validators 的错误、ASP.NET CompareValidator validate Currency等更多相关知识的信息可以在本站进行查询。

本文标签: