typescript Angular 2 将参数传递给验证器函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37119958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 Pass parameter to a validator function
提问by Bohms27
I have an array in my formcomponent class and want to be able to pass that array to a validator function. When adding multiple validators to the form, I am using Validators.compose function. This only accepts the name of the validator function though, and not any parameters to pass. Is it possible to add parameters to the function calls inside of the "compose" function?
我的 formcomponent 类中有一个数组,并且希望能够将该数组传递给验证器函数。向表单添加多个验证器时,我使用的是 Validators.compose 函数。不过,这只接受验证器函数的名称,而不接受任何要传递的参数。是否可以向“compose”函数内部的函数调用添加参数?
export class ClientFormComponent
{
clientForm: ControlGroup;
npi: AbstractControl;
name: AbstractControl;
constructor(private _clientService: ClientService, _fb: FormBuilder) {
this.clientForm = _fb.group({ 'name': ['', Validators.compose([Validators.required])], 'npi': ['', Validators.compose([Validators.required, npiNumValidator, Validators.maxLength(10), Validators.minLength(10)])]});
this.name = this.clientForm.controls['name'];
this.npi = this.clientForm.controls['npi'];
}
@Input() clientList;
active = true;
onSubmit(value: Client) {
this._clientService.addDeleteClient(value, true)
.subscribe(
client => this.clientList.push(client));
}
}
function npiNumValidator(control: Control): { [s: string]: boolean } {
if (isNaN(control.value)) {
return { npiNAN: true };
}
}
Thanks for any help!
谢谢你的帮助!
回答by Günter Z?chbauer
Just move it to a class
只需将其移至班级
class NpiNumValicator {
constructor(private someField: someType) {}
npiNumValidator(control: Control): { [s: string]: boolean } {
if (isNaN(control.value)) {
return { npiNAN: true };
}
}
}
then use it like
然后像这样使用它
this.clientForm = _fb.group({ 'name': ['',
Validators.compose([Validators.required])], 'npi': ['',
Validators.compose([Validators.required,
new NpiNumValidator(someArg).npiNumValidator,
Validators.maxLength(10), Validators.minLength(10)
])
]});
to be able to use this
within npiNumValidator
you can use
能够this
在npiNumValidator
你可以使用的范围内使用
var npiNumVal = new NpiNumValidator(someArg);
this.clientForm = _fb.group({ 'name': ['',
Validators.compose([Validators.required])], 'npi': ['',
Validators.compose([Validators.required,
npiNumVal.npiNumValidator.bind(npiNumVal),
Validators.maxLength(10), Validators.minLength(10)
])
]});
回答by Ankit Singh
Is it possible to add parameters to the function calls inside of the "compose" function?
是否可以向“compose”函数内部的函数调用添加参数?
Validator Declaration:straight out of Angular Code
验证器声明:直接来自 Angular 代码
/* Validator that requires controls to have a value of a minimum length. */
static minLength(minLength: number): ValidatorFn {
return (control: modelModule.AbstractControl): {[key: string]: any} => {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length < minLength ?
{"minlength": {"requiredLength": minLength, "actualLength": v.length}} :
null;
};
}
Usage:
用法:
Validators.compose([Validators.minLength(4)]
NOTE: to understand it better, see How do JavaScript closures work?
注意:为了更好地理解它,请参阅JavaScript 闭包如何工作?
回答by Eric G
In some cases the data that needs to be passed to the validator is dynamic and can be found in the class that is calling the validator. In those instances I just have simply used "bind(this)" when adding the validator. Here is a formBuilder example:
在某些情况下,需要传递给验证器的数据是动态的,可以在调用验证器的类中找到。在这些情况下,我只是在添加验证器时使用了“bind(this)”。这是一个 formBuilder 示例:
this.profileFormGroups.push( this.formBuilder.group({
name: [profile.name,
Validators.compose([
Validators.required,
Validators.maxLength(30),
Validators.pattern('[a-zA-Z ]*')
]),
this.myNameValidator.bind(this)
]
}) );
}, this);
Then in your validator just reference the dynamic parameter:
然后在您的验证器中只引用动态参数:
//my Async Validator
//我的异步验证器
myNameValidator(control: FormControl): any {
let vm = this;
return new Promise(resolve => {
if ( vm.mydynamicvalue === control.name ) { ... }
resolve({"Invalid User":true});
else
resolve(null)
});
}
}
回答by Thierry Templier
You also leverage a method of your component to create the validation function. This way you will be able to access properties of this component using an arrow function.
您还可以利用组件的方法来创建验证功能。这样您就可以使用箭头函数访问该组件的属性。
Here is a sample:
这是一个示例:
@Component({ ... })
export class MyComponent {
constructor(private fb:FormBuilder) {
this.form = this.fb.group({
fieldName: [ '', this.createValidator() ]
});
}
createValidator() {
return (control) => {
var arr = this.arr;
(...)
};
}
}
回答by Zahema
The top answer meant I will have to create a class for each validator which I didn't like. Here is my approach:
最佳答案意味着我必须为每个我不喜欢的验证器创建一个类。这是我的方法:
public static npiNumValidator(
x: any
): (AbstractControl) => ValidationErrors | null {
return (control: AbstractControl): ValidationErrors | null => {
return !!x ? null : { error: true};
};
}
Use as:
用于:
this.form = this.formBuilder.group({
email: [undefined, [ClassName.npiNumValidator('value')]],
});