简体   繁体   English

角反应形式-获取用于自定义验证程序的formControl

[英]Angular reactive forms - get formControl for custom validator

I have implemented a generic custom validator as a function looking like this: 我已经将通用的自定义验证器实现为如下所示的函数:

export function validate(control: AbstractControl, validation: boolean,
                         errObj: { [key: string]: boolean }): null | { [key: string]: boolean } {
    const toCheck: string = control.value;
    if (!toCheck || validation) {
        return null;
    } else {
        return errObj;
    }
}

pretty easy and straight forward: It gets the value from the form control and if the value is defined or it passes the condition given on a parameter it returns null, else an errorobj. 非常简单直接:它从表单控件获取值,并且如果定义了该值或它通过了参数给出的条件,则返回null,否则返回errorobj。


Now i want to assign this custom validator on a control, but I dont know how to pass the current Abstractcontrol . 现在,我想在控件上分配此自定义验证器,但是我不知道如何传递当前的Abstractcontrol I've tried something like this: 我已经尝试过这样的事情:

private formBuilder: FormBuilder = new FormBuilder();

public setForm(form: SomeType): FormGroup {
    return this.formBuilder.group({
        days: [form.days],
        ...
        useDefaultRule: [form.useDefaultRule],
        urls: this.formBuilder.group({
            webUrl: [form.urls.webUrl, [validate(new FormControl(),
                hasWebURLPattern(new FormControl().value),
                {webUrl: true})]]
        })
    });
}

But this does not work. 但这是行不通的。 How do I pass the current formcontrol as a parameter? 如何传递当前的formcontrol作为参数?

I think that you didn't write you validator in the right way. 我认为您没有以正确的方式编写验证程序。

Try this instead. 试试这个吧。

export function validate(callback: Function, error: string): ValidatorFn {
  return (control: FormControl) => {
    return control.value && callback(control.value) ? { [error]: true } : null;
  };
}

You can call it with 你可以用

webUrl: ['', [validate(hasWebURLPattern, 'webUrl')]]

It works by giving in a function, that will be called with the value of the form control directly into the validator. 它通过提供一个函数来工作,该函数将使用表单控件的值直接调用到验证器中。 You also provide directly an error string, reducing effectively the code complexity. 您还可以直接提供错误字符串,从而有效降低代码复杂性。

Also, don't forget that you will lose your this context : if your callback has this references in it, add this to your call : 另外,不要忘记您会丢失this上下文:如果您的回调函数中包含this引用,请将其添加到您的调用中:

webUrl: ['', [validate(hasWebURLPattern.bind(this), 'webUrl')]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM