mirror of
https://github.com/angular/angular
synced 2026-05-24 09:28:37 +00:00
- Introduce `InjectionToken<T>` which is a parameterized and type-safe
version of `OpaqueToken`.
DEPRECATION:
- `OpaqueToken` is now deprecated, use `InjectionToken<T>` instead.
- `Injector.get(token: any, notFoundValue?: any): any` is now deprecated
use the same method which is now overloaded as
`Injector.get<T>(token: Type<T>|InjectionToken<T>, notFoundValue?: T): T;`.
Migration
- Replace `OpaqueToken` with `InjectionToken<?>` and parameterize it.
- Migrate your code to only use `Type<?>` or `InjectionToken<?>` as
injection tokens. Using other tokens will not be supported in the
future.
BREAKING CHANGE:
- Because `injector.get()` is now parameterize it is possible that code
which used to work no longer type checks. Example would be if one
injects `Foo` but configures it as `{provide: Foo, useClass: MockFoo}`.
The injection instance will be that of `MockFoo` but the type will be
`Foo` instead of `any` as in the past. This means that it was possible
to call a method on `MockFoo` in the past which now will fail type
check. See this example:
```
class Foo {}
class MockFoo extends Foo {
setupMock();
}
var PROVIDERS = [
{provide: Foo, useClass: MockFoo}
];
...
function myTest(injector: Injector) {
var foo = injector.get(Foo);
// This line used to work since `foo` used to be `any` before this
// change, it will now be `Foo`, and `Foo` does not have `setUpMock()`.
// The fix is to downcast: `injector.get(Foo) as MockFoo`.
foo.setUpMock();
}
```
PR Close #13785
177 lines
5.6 KiB
TypeScript
177 lines
5.6 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright Google Inc. All Rights Reserved.
|
|
*
|
|
* Use of this source code is governed by an MIT-style license that can be
|
|
* found in the LICENSE file at https://angular.io/license
|
|
*/
|
|
|
|
import {InjectionToken} from '@angular/core';
|
|
import {toPromise} from 'rxjs/operator/toPromise';
|
|
|
|
import {AsyncValidatorFn, Validator, ValidatorFn} from './directives/validators';
|
|
import {StringMapWrapper} from './facade/collection';
|
|
import {isPresent} from './facade/lang';
|
|
import {AbstractControl} from './model';
|
|
import {isPromise} from './private_import_core';
|
|
|
|
function isEmptyInputValue(value: any): boolean {
|
|
// we don't check for string here so it also works with arrays
|
|
return value == null || value.length === 0;
|
|
}
|
|
|
|
/**
|
|
* Providers for validators to be used for {@link FormControl}s in a form.
|
|
*
|
|
* Provide this using `multi: true` to add validators.
|
|
*
|
|
* ### Example
|
|
*
|
|
* {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'}
|
|
* @stable
|
|
*/
|
|
export const NG_VALIDATORS = new InjectionToken<Array<Validator|Function>>('NgValidators');
|
|
|
|
/**
|
|
* Providers for asynchronous validators to be used for {@link FormControl}s
|
|
* in a form.
|
|
*
|
|
* Provide this using `multi: true` to add validators.
|
|
*
|
|
* See {@link NG_VALIDATORS} for more details.
|
|
*
|
|
* @stable
|
|
*/
|
|
export const NG_ASYNC_VALIDATORS =
|
|
new InjectionToken<Array<Validator|Function>>('NgAsyncValidators');
|
|
|
|
/**
|
|
* Provides a set of validators used by form controls.
|
|
*
|
|
* A validator is a function that processes a {@link FormControl} or collection of
|
|
* controls and returns a map of errors. A null map means that validation has passed.
|
|
*
|
|
* ### Example
|
|
*
|
|
* ```typescript
|
|
* var loginControl = new FormControl("", Validators.required)
|
|
* ```
|
|
*
|
|
* @stable
|
|
*/
|
|
export class Validators {
|
|
/**
|
|
* Validator that requires controls to have a non-empty value.
|
|
*/
|
|
static required(control: AbstractControl): {[key: string]: boolean} {
|
|
return isEmptyInputValue(control.value) ? {'required': true} : null;
|
|
}
|
|
|
|
/**
|
|
* Validator that requires control value to be true.
|
|
*/
|
|
static requiredTrue(control: AbstractControl): {[key: string]: boolean} {
|
|
return control.value === true ? null : {'required': true};
|
|
}
|
|
|
|
/**
|
|
* Validator that requires controls to have a value of a minimum length.
|
|
*/
|
|
static minLength(minLength: number): ValidatorFn {
|
|
return (control: AbstractControl): {[key: string]: any} => {
|
|
if (isEmptyInputValue(control.value)) {
|
|
return null; // don't validate empty values to allow optional controls
|
|
}
|
|
const length: number = control.value ? control.value.length : 0;
|
|
return length < minLength ?
|
|
{'minlength': {'requiredLength': minLength, 'actualLength': length}} :
|
|
null;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Validator that requires controls to have a value of a maximum length.
|
|
*/
|
|
static maxLength(maxLength: number): ValidatorFn {
|
|
return (control: AbstractControl): {[key: string]: any} => {
|
|
const length: number = control.value ? control.value.length : 0;
|
|
return length > maxLength ?
|
|
{'maxlength': {'requiredLength': maxLength, 'actualLength': length}} :
|
|
null;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Validator that requires a control to match a regex to its value.
|
|
*/
|
|
static pattern(pattern: string|RegExp): ValidatorFn {
|
|
if (!pattern) return Validators.nullValidator;
|
|
let regex: RegExp;
|
|
let regexStr: string;
|
|
if (typeof pattern === 'string') {
|
|
regexStr = `^${pattern}$`;
|
|
regex = new RegExp(regexStr);
|
|
} else {
|
|
regexStr = pattern.toString();
|
|
regex = pattern;
|
|
}
|
|
return (control: AbstractControl): {[key: string]: any} => {
|
|
if (isEmptyInputValue(control.value)) {
|
|
return null; // don't validate empty values to allow optional controls
|
|
}
|
|
const value: string = control.value;
|
|
return regex.test(value) ? null :
|
|
{'pattern': {'requiredPattern': regexStr, 'actualValue': value}};
|
|
};
|
|
}
|
|
|
|
/**
|
|
* No-op validator.
|
|
*/
|
|
static nullValidator(c: AbstractControl): {[key: string]: boolean} { return null; }
|
|
|
|
/**
|
|
* Compose multiple validators into a single function that returns the union
|
|
* of the individual error maps.
|
|
*/
|
|
static compose(validators: ValidatorFn[]): ValidatorFn {
|
|
if (!validators) return null;
|
|
const presentValidators = validators.filter(isPresent);
|
|
if (presentValidators.length == 0) return null;
|
|
|
|
return function(control: AbstractControl) {
|
|
return _mergeErrors(_executeValidators(control, presentValidators));
|
|
};
|
|
}
|
|
|
|
static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn {
|
|
if (!validators) return null;
|
|
const presentValidators = validators.filter(isPresent);
|
|
if (presentValidators.length == 0) return null;
|
|
|
|
return function(control: AbstractControl) {
|
|
const promises = _executeAsyncValidators(control, presentValidators).map(_convertToPromise);
|
|
return Promise.all(promises).then(_mergeErrors);
|
|
};
|
|
}
|
|
}
|
|
|
|
function _convertToPromise(obj: any): Promise<any> {
|
|
return isPromise(obj) ? obj : toPromise.call(obj);
|
|
}
|
|
|
|
function _executeValidators(control: AbstractControl, validators: ValidatorFn[]): any[] {
|
|
return validators.map(v => v(control));
|
|
}
|
|
|
|
function _executeAsyncValidators(control: AbstractControl, validators: AsyncValidatorFn[]): any[] {
|
|
return validators.map(v => v(control));
|
|
}
|
|
|
|
function _mergeErrors(arrayOfErrors: any[]): {[key: string]: any} {
|
|
const res: {[key: string]: any} =
|
|
arrayOfErrors.reduce((res: {[key: string]: any}, errors: {[key: string]: any}) => {
|
|
return isPresent(errors) ? StringMapWrapper.merge(res, errors) : res;
|
|
}, {});
|
|
return Object.keys(res).length === 0 ? null : res;
|
|
}
|