Angular2 - FormControl Validation on blur

前端 未结 6 1766
耶瑟儿~
耶瑟儿~ 2020-11-27 14:26

I\'m looking at adding some basic email validation to check that the user has put in a correct email address. Currently using the method below, the validation updates as the

6条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 14:59

    EDIT 2

    As Alex and the official documentation says, Angular version 5.0.0 has new option for your ngModel updateOn: 'blur'

    this.email = new FormControl(null, {
       validators: Validators.required,
       updateOn: 'blur'
    });
    

    Also you can use other update options: change (default), blur, submit.


    Original

    I use directive where remove whole validation on focus and return it back after blur event. It based on Cristian Deschamps answer.

    I update validity only on blur, so if value was invalid before focus it will be invalid after. But if you start input, validity will be updated.

    For some reasons clearing order make sense, so I clear async validators first.

    Any provided suggestion will be helpful =)

    import { Directive } from '@angular/core';
    import { NgControl } from '@angular/forms';
    
    @Directive({
      selector: '[validate-onblur]',
      host: {
        '(focus)': 'onFocus($event)',
        '(blur)': 'onBlur($event)'
      }
    })
    export class ValidateOnBlurDirective {
        private validators: any;
        private asyncValidators: any;
        constructor(public formControl: NgControl) {
        }
        onFocus($event) {
          this.validators = this.formControl.control.validator;
          this.asyncValidators = this.formControl.control.asyncValidator;
          this.formControl.control.clearAsyncValidators();
          this.formControl.control.clearValidators();
        }
    
        onBlur($event) {
          this.formControl.control.setAsyncValidators(this.asyncValidators);
          this.formControl.control.setValidators(this.validators);
          this.formControl.control.updateValueAndValidity();
        }
    }
    

    Also, please stay tuned on this Angular 2 github thread about onBlur validation


    EDIT 1

    There is another problem - if I just click on the field and after click away - validation will be called. If you have any notification about it (or server calls) - it would appear every time you do it. So you can add wasChanged property and use it like this:

        @Directive({
            selector: '[validate-onblur]',
            host: {
                '(focus)': 'onFocus($event)',
                '(blur)': 'onBlur($event)',
                '(keyup)': 'onKeyup($event)',
                '(change)': 'onChange($event)',
                '(ngModelChange)': 'onNgModelChange($event)'
            }
        })
        export class ValidationOnBlurDirective {
            private validators: any;
            private asyncValidators: any;
            private wasChanged: any;
            constructor(public formControl: NgControl) {
            }
            onFocus($event) {
                this.wasChanged = false;
                this.validators = this.formControl.control.validator;
                this.asyncValidators = this.formControl.control.asyncValidator;
                this.formControl.control.clearAsyncValidators();
                this.formControl.control.clearValidators();
            }
            onKeyup($event) {
                this.wasChanged = true; // keyboard change
            }
            onChange($event) {
                this.wasChanged = true; // copypaste change
            }
            onNgModelChange($event) {
                this.wasChanged = true; // ng-value change
            }
            onBlur($event) {
                this.formControl.control.setAsyncValidators(this.asyncValidators);
                this.formControl.control.setValidators(this.validators);
                if (this.wasChanged)
                    this.formControl.control.updateValueAndValidity();
            }
        }
    

提交回复
热议问题