I\'m trying to add form validations which don\'t invalidate the form. The validation should only appear as warnings.
E.g. an age validation. An age greater than 90 shows
I have done it by creating custom validator, which always return null
. Also this validator creates additional property warnings
. Then just simple check this property from your view.
export interface AbstractControlWarn extends AbstractControl { warnings: any; }
export function tooBigAgeWarning(c: AbstractControlWarn) {
if (!c.value) { return null; }
let val = +c.value;
c.warnings = val > 90 && val <= 120 ? { tooBigAge: {val} } : null;
return null;
}
export function impossibleAgeValidator(c: AbstractControl) {
if (tooBigAgeWarning(c) !== null) { return null; }
let val = +c.value;
return val > 120 ? { impossibleAge: {val} } : null;
}
@Component({
selector: 'my-app',
template: `
Age:
Error! Age is required
Error! Age is greater then 120
Warning! Age is greater then 90
`,
})
export class App {
age: FormControl;
constructor(private _fb: FormBuilder) { }
ngOnInit() {
this.form = this._fb.group({
age: ['', [
Validators.required,
tooBigAgeWarning,
impossibleAgeValidator]]
})
this.age = this.form.get("age");
}
}
Example: https://plnkr.co/edit/me0pHePkcM5xPQ7nzJwZ?p=preview