Forms: Support asynchronous validation
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.
:+1:
It would be cool if validator could return a promise:
function SomeValidator(control: FormControl) {
return Promise.resolve().then(() => {
// some async stuff
return isValid;
});
}
Removed from M7. We should do this, but it's not a blocker for M7.
+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.
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 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.
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 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.
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 return 'thened' promise or package it with Observable.
return q.then(res => res);
OR
return Observable.fromPromise(q);
I have tried return Observable.fromPromise(q); and the same. @caolixiang Have you a plunker o something like that with a working example?
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
@danicomas async example Enter whatever but not string starts with '123' within input, and the async validator will be resolve after 2000ms.
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.
Maybe should close this one ?
@Raminsiach does it work now? cuz i'm trying something like that.
@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 :)
anyone got any solution for this?
i tried exactly what @attapanbank have mentioned here. But validation error message is not displayed.
Async validation is implemented
/cc @kara