Angular2 - FormControl Validation on blur

前端 未结 6 1751
耶瑟儿~
耶瑟儿~ 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:49

    Found a way, in rc6.

    1- Create a directive: validate-onblur.directive.ts

    @Directive({
      selector: '[validate-onblur]',
      host: {
        '(focus)': 'onFocus($event)',
        '(blur)': 'onBlur($event)'
      }
    })
    export class ValidateOnBlurDirective {
        constructor(public formControl: NgControl) {
        }
    
        onFocus($event) {
          this.formControl.control.markAsUntouched(false);
        }
    
        onBlur($event) {
          this.formControl.control.markAsTouched(true);
        }
    }
    

    Then in your html template just add the directive to your form, my example use the ReactiveFormsModule model.

    Then add this to your error message:

    
    
    
            ...
    
    

提交回复
热议问题