条件形式验证器Angular2

时间:2016-06-23 16:06:54

标签: javascript validation angular conditional

我正在尝试根据所选的单选按钮运行表单验证器,因此如果选择了instagram,则运行一个验证器,如果选择了facebook,则运行不同的验证器。我的组件模板如下:

<div class="form-group" [ngClass]="{ 'has-error' : !requestURL.valid && submitAttempt }">

                        <div class="radio">

                            <label for="instagram">
                                <input type="radio" 
                                    name="socialmedia" 
                                    id="instagram" 
                                    value="instagram" 
                                    [checked]="selectedSourceType === 'instagram'"
                                    (click)="updateSelectedSourceType('instagram')">

                                    <i class="fa fa-instagram"></i>
                            </label>

                            <label for="facebook">
                                <input type="radio" 
                                    name="socialmedia" 
                                    id="facebook" 
                                    value="facebook" 
                                    [checked]="selectedSourceType === 'facebook'"
                                    (click)="updateSelectedSourceType('facebook')">

                                    <i class="fa fa-facebook"></i>
                            </label>

                        </div>

                        <label for="requestSource">Submit URL</label>
                        <span *ngIf="requestURL.hasError('alreadyTracked')" class="already-following">Already Following This User</span>

                        <input type="text" 
                            id="requestSource" 
                            class="form-control" 
                            placeholder="Enter a website, Facebook Page or Instagram handle" 
                            ngControl="requestURL">

因此,在单击时,切换selectedSourceType,其值应确定运行哪个验证器。但是,由于构造函数,运行时的原始值是运行的验证器,即使选择了其他单选按钮也是如此。有人有任何可能的解决方案吗?这是我班级的内容,验证器现在只是一个字符串检查,并按预期单独工作:

theForm: ControlGroup;
requestURL: Control;
submitAttempt: boolean = false;
isLoading: boolean = false;
selectedSourceType:string = 'facebook';

validationUrls = {
    instagram: 'post-ig-url?src=',
    facebook: 'post-fb-url?src='
}

constructor(private _applicationService:AppService,
    private _elRef:ElementRef,
    private _router:Router,
    private _http:Http,
    private _builder:FormBuilder) {

    super(_elRef, _applicationService, _router);

    this.createRequestURLControl(CustomValidators.facebookURL);

    this.theForm = _builder.group({
        requestURL: this.requestURL
    });
}


requestSource(form){
    console.log('Selected source:', this.selectedSourceType);

    this.isLoading = true;
    this.submitAttempt = true;

    let sub = this._http.post(this.validationUrls[this.selectedSourceType] + form.requestURL, '')
        .subscribe(data => {
            console.log("URL Submitted for review", data);
            this.isLoading = false;
        }, error => {
            console.info(error.json().message);
        });

    this.addSubscription(sub);
}

createRequestURLControl(validator:any) {
    this.requestURL = new Control('', Validators.compose([validator, Validators.required]) );
}

updateSelectedSourceType(sourceType:string) {
    this.selectedSourceType = sourceType;

    // update validators
    if (sourceType === 'facebook') {
        this.createRequestURLControl(CustomValidators.facebookURL);
    } else {
        this.createRequestURLControl(CustomValidators.instagramURL);
    }
    // clear input
}

1 个答案:

答案 0 :(得分:2)

只需将验证器作为组件的方法,或当前作用域中的闭包,以便它可以访问组件的值。

class MyComponent {
  someValidator(c:Control) {
    if(this.radio...) {
      ...
    }
  }

  createRequestURLControl(validator:any) {
      this.requestURL = new Control('', Validators.compose([(c:Control) => this.someValidator(c), Validators.required]) );
  }
}

我没有调查你想要有条件的确切验证器或者如何评估条件,但你应该明白这一点。

重要的是使用()=>,以便this继续在验证方法中工作。