angular icon indicating copy to clipboard operation
angular copied to clipboard

Forms: Support asynchronous validation

Open kpko opened this issue 11 years ago • 21 comments

I saw the demos of the new Forms API in Angular 2 on http://angularjs.blogspot.de/2015/03/forms-in-angular-2.html and wondered, if asynchronous validation will be supported. A common use-case for asynchronous validation would be a user registration form. The user name should be validated on the server.

We need a new state to indicate that the form/a particular field is currently validating. This enables us to show some kind of loading spinner on the form or a field. (pending validation)

Asynchronous validation was implemented in Angular 1.3, it would be great if we had this in Angular 2 Forms too. A great example of this functionality from Angular 1.3 (the $pending state for particular fields) is shown here: http://www.yearofmoo.com/2014/09/taming-forms-in-angularjs-1-3.html#asnychronous-validation-via-asyncvalidators

This topic was already discussed in the Angular 2 Forms design doc with a few suggestions regarding the implementation: https://docs.google.com/document/d/1US9h0ORqBltl71TlEU6s76ix8SUnOLE2jabHVg9xxEA/ Maybe we can discuss how this feature should be laid out.

kpko avatar Mar 24 '15 00:03 kpko

:+1:

It would be cool if validator could return a promise:

function SomeValidator(control: FormControl) {
  return Promise.resolve().then(() => {
    // some async stuff
    return isValid;
  });
}

alexpods avatar Mar 24 '15 05:03 alexpods

Removed from M7. We should do this, but it's not a blocker for M7.

yjbanov avatar Mar 26 '15 17:03 yjbanov

+1. It would be great to do something like this:

this.control.asyncValidator = Validators.composeAsync([
  someMethodReturnsPromise
]);

In Angular 1.3 we have the ability to add validators to the inputs dynamically.

pkantsedalov avatar Dec 14 '15 19:12 pkantsedalov

I think this is already there ... check this implementation and usage.

rolandjitsu avatar Dec 14 '15 19:12 rolandjitsu

rolandjitsu, your example is great and works, but my situation is quite specific: I have file input validators and I need to read a file from the file input. When I add the validator in the way your example exposes I get "C:\fakepath\MyPhoto.JPG" instead of File/FileList instance for its reading. And one more issue: if I have another validators added with Validators.compose() their errors are overwritten by my async validator. Could you help me with it, please?

pkantsedalov avatar Dec 14 '15 20:12 pkantsedalov

@pkantsedalov I see, maybe you should take a look at #5482. I do not think that file inputs are supported by angular 2 right now (probably never will), but you could build your own input directive that uses FileReader to read the file, parse it (to whatever format you need) then set the ngModel to that parsed value. This would mean your validator would then see what you expect and not the path to the file.

I am not sure if there is a better way of doing it, but it's the only I can think of. As for building the custom directive, take a look at the referenced issues from the issue I referenced and look at some of the input directives provided by angular 2.

rolandjitsu avatar Dec 14 '15 20:12 rolandjitsu

Thanx a lot, rolandjitsu, I've implemented it now using your validation directive approach with some changes (because I don't need the default Control in validate function, but my own got from directive properties - in the default one I don't have the ability to access the file at all, only "C:\fakepath" etc). Guys, attention: after some investigation I think now rolandjitsu's way is the only way to add async validators dynamically.

Here is example of adding errors to the control got from outside

/**
   * 
   * @param control
   * @returns {Promise<T>}
   */
  validate(control: Control): {[key: string]: any} {

    return new Promise( resolve => {
      if (this._doesInputFilled(this.control)) {
        this._validate(this.control.value).then(resolve, err => {
          this.control.setErrors(Object.assign(this.control.errors, err), true);
          resolve(err);
        })
      } else resolve(null);

    });

  }
``

pkantsedalov avatar Dec 14 '15 21:12 pkantsedalov

@pkantsedalov no worries, but I think you can also find this solution within the angular examples or somewhere, I cannot remember where I did, probably on one of the commits or in the changelog.

rolandjitsu avatar Dec 14 '15 22:12 rolandjitsu

Async

static uniqueSlug(control: Control): Promise<ValidationResult> {

   let q = new Promise((resolve, reject) => {
     setTimeout(() => {
       if (control.value === 'barcelona') {
         resolve( {"uniqueSlug": true} );
       } else {
         resolve(null);
       }
     }, 500)
   });

   return q;
 }

Component

slug: ["", CustomValidator.uniqueSlug]

HTML

<input ngControl="slug" type="text" class="form-control">
                  <p *ngIf="personForm.controls.slug.pending">
                    Verifying data from the server...
                  </p>
<show-error control="slug" [errors]="['slug', 'uniqueslug']" class="text-danger"></show-error>
{{personForm.controls.slug.valid}}

Pending and valid always are false and not error is shown in console. Any suggestion?

danicomas avatar Jan 22 '16 15:01 danicomas

@danicomas return 'thened' promise or package it with Observable.

return q.then(res => res);

OR

return Observable.fromPromise(q);

caolixiang avatar Jan 27 '16 07:01 caolixiang

I have tried return Observable.fromPromise(q); and the same. @caolixiang Have you a plunker o something like that with a working example?

danicomas avatar Jan 27 '16 08:01 danicomas

For asynchronous validation, observables are the only way to go. Consider the example below

var a = 1;
var b = 2;
var c = a + b;
// validate
console.log(valid(c));
// reset
c = a = b null;
a = 5;
b = 2;

c = a + b;
console.log(valid(c));

c = a = b null;
a = 1;
b = 49

c = a + b;
console.log(valid(c));
var a = new BehaviorSubject(1);
var b = new BehaviorSubject(2);
var c = Observable.merge(a, b).startWith(0).scan((x, y) => x + y);

//   validations are "reducers" that can also be async with Observables/Promises or sync
//      \/  
c.map(valid).subscribe(val => console.log(val)) // <- this callback runs when a value changes

a.next(5);
b.next(49);

things to notice

  • how code is needed.
  • this is simply redux/cyclejs/elm/buzz wordy architecture
  • solves all the problems in Angular 1 with one API
  • time independent
  • you can also cancel or even retry built-in to the Observable itself not the framework

replace a/b with controls and c as the control groups. Why even bother with Promises if we're going to end up with the same awkward API as Angular 1 where we have asyncvalidators and validators and if you want it to fail you reject. This is the perfect use-case for Observables

PatrickJS avatar Jan 27 '16 09:01 PatrickJS

@danicomas async example Enter whatever but not string starts with '123' within input, and the async validator will be resolve after 2000ms.

caolixiang avatar Jan 27 '16 10:01 caolixiang

How does it work with http? lets say I want to validate a username field. The validator function needs to return a promise and inside that promise I need to do an http call to server to see if the email exist. I cant get this to work ?

isTaken(control: Control) {
        return new Promise(resolve  => {
            let headers = new Headers();
            headers.append('Content-Type', 'application/json')
            this._http.get('http://localhost:8000/emailValidate', {headers: headers})
            .map(res => res.json())
            .subscribe(data => {
                console.log(data);
                if(data.email == true) {
                    resolve({taken: true})
                }
                else {resolve({taken: false}); }        
            })
        });
    }

Why this is not working? it does not do any http call.

Raminsiach avatar Feb 13 '16 22:02 Raminsiach

Maybe should close this one ?

eelwayadmin avatar Mar 24 '16 13:03 eelwayadmin

@Raminsiach does it work now? cuz i'm trying something like that.

chanlito avatar Apr 28 '16 04:04 chanlito

@BruceHem @Raminsiach try like this to use http

  import {Injector} from 'angular2/core'
  import {Control} from 'angular2/common';
  import {Http, HTTP_PROVIDERS, Headers, RequestOptions, Response} from 'angular2/http';

 interface ValidationResult {
       [key: string]: boolean;
  }

  export class ValidationService {

  static isTaken(control: Control): Promise<ValidationResult> {

    // Manually inject Http
    let injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
    let http = injector.get(Http);

    let body = JSON.stringify({ "username": control.value });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return new Promise(resolve => {
        http.post('Your url', body, options)
            .map(res => res.json())
            .subscribe(data => {
                console.log(data);
                if (data.username== control.value) {
                    resolve({ taken: true })
                }
                else { 
                    resolve({ taken: null}); 
                }
            },
            error => { resolve(null); }
            )
    });
}
}

Hope this might help :)

attapanbank avatar May 10 '16 09:05 attapanbank

anyone got any solution for this?

reshmiasish avatar Jun 02 '16 07:06 reshmiasish

i tried exactly what @attapanbank have mentioned here. But validation error message is not displayed.

reshmiasish avatar Jun 02 '16 07:06 reshmiasish

Async validation is implemented

/cc @kara

vicb avatar Jun 27 '16 16:06 vicb