feat(forms): introduce min and max validators (#15813)

PR Close #15813
This commit is contained in:
Toxicable
2017-04-06 09:41:10 -06:00
committed by Miško Hevery
parent 6e2abcd5fc
commit 81925fa66d
7 changed files with 293 additions and 2 deletions

View File

@ -57,6 +57,7 @@ export const CHECKBOX_REQUIRED_VALIDATOR: Provider = {
multi: true
};
/**
* A Directive that adds the `required` validator to any controls marked with the
* `required` attribute, via the {@link NG_VALIDATORS} binding.
@ -94,6 +95,84 @@ export class RequiredValidator implements Validator {
registerOnValidatorChange(fn: () => void): void { this._onChange = fn; }
}
export const MIN_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MinValidator),
multi: true
};
/**
* A directive which installs the {@link MinValidator} for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `min` attribute.
*
* @experimental
*/
@Directive({
selector: '[min][formControlName],[min][formControl],[min][ngModel]',
providers: [MIN_VALIDATOR],
host: {'[attr.min]': 'min ? min : null'}
})
export class MinValidator implements Validator,
OnChanges {
private _validator: ValidatorFn;
private _onChange: () => void;
@Input() min: string;
ngOnChanges(changes: SimpleChanges): void {
if ('min' in changes) {
this._createValidator();
if (this._onChange) this._onChange();
}
}
validate(c: AbstractControl): ValidationErrors|null { return this._validator(c); }
registerOnValidatorChange(fn: () => void): void { this._onChange = fn; }
private _createValidator(): void { this._validator = Validators.min(parseInt(this.min, 10)); }
}
export const MAX_VALIDATOR: Provider = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MaxValidator),
multi: true
};
/**
* A directive which installs the {@link MaxValidator} for any `formControlName`,
* `formControl`, or control with `ngModel` that also has a `min` attribute.
*
* @experimental
*/
@Directive({
selector: '[max][formControlName],[max][formControl],[max][ngModel]',
providers: [MAX_VALIDATOR],
host: {'[attr.max]': 'max ? max : null'}
})
export class MaxValidator implements Validator,
OnChanges {
private _validator: ValidatorFn;
private _onChange: () => void;
@Input() max: string;
ngOnChanges(changes: SimpleChanges): void {
if ('max' in changes) {
this._createValidator();
if (this._onChange) this._onChange();
}
}
validate(c: AbstractControl): ValidationErrors|null { return this._validator(c); }
registerOnValidatorChange(fn: () => void): void { this._onChange = fn; }
private _createValidator(): void { this._validator = Validators.max(parseInt(this.max, 10)); }
}
/**
* A Directive that adds the `required` validator to checkbox controls marked with the
* `required` attribute, via the {@link NG_VALIDATORS} binding.