Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay input validation in Angular 2+

In AngularJS, you could set a input with a directive to delay validation with

link(scope, elem, attr, ngModel) {
    ngModel.$overrideModelOptions({
        updateOn: 'default blur',
        debounce: {
            blur: 0,
            default: 500,
        },
    });
}

What this does is: when the input changes, a 500 millisecond delay is given before the input validates from valid/invalid.

In Angular2+, this seems more difficult. I think I can listen to the changes with observables and update validation that way, but how do I tell the initial input to not validate?

like image 634
brendan shaub Avatar asked Apr 05 '18 20:04

brendan shaub


People also ask

What is dirty in angular?

When the user changes the value in the watched field, the control is marked as "dirty" When the user blurs the form control element, the control is marked as "touched"

What is difference between touched and dirty in angular?

The difference between touched and dirty is that with touched the user doesn't need to actually change the value of the input control. touched is true of the field has been touched by the user, otherwise it's false. The opposite of touched is the property untouched .

What is AbstractControl in angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.

What is ValidatorFn in angular?

ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }


1 Answers

Since Angular 5.0 have more control on when to run your form validations. You can configure the validations to run either on blur or submit using updateOn options.

  1. Reactive Forms Examples:

Will run validators on form control blur:

new FormControl(null, {
  updateOn: 'blur'
});

Will run validators after the form is submitted:

new FormGroup({
  fistName: new FormControl(),
  lastName: new FormControl()
}, { updateOn: 'submit' });
  1. Template Driven Forms:

Will run validators on form control blur:

<input [(ngModel)]="firstName" [ngModelOptions]="{updateOn: 'blur'}">

Will run validators after the form is submitted:

More info in the docs

As someone in the comments mentioned, you can also subscribe to the form value changes stream, but if you are interested in delayed form validation, you should probably be looking into the updateOn property.

like image 121
Tomasz Kula Avatar answered Sep 17 '22 22:09

Tomasz Kula