Angular 2 - Form validation for warnings/hints

前端 未结 4 606
一生所求
一生所求 2021-02-12 21:16

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

4条回答
  •  悲&欢浪女
    2021-02-12 21:57

    The accepted answer from Sergey Voronezhskiy works perfect in development mode but if you try build in --prod mode you will get this error.

    ...  Property 'warnings' does not exist on type 'FormControl'.
    

    In order to fix this error I did adjustments to the original code (App class), basically to fix loosely typed variables. This is the new version:

    export class FormControlWarn extends FormControl { warnings: any; }
    
    export function tooBigAgeWarning(c: FormControlWarn ) {
        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 { get age(): FormControlWarn{ return this.form.get("age"); } constructor(private _fb: FormBuilder) { } ngOnInit() { this.form = this._fb.group({ age: new FormControlWarn('', [ Validators.required, tooBigAgeWarning, impossibleAgeValidator]) }); } }

提交回复
热议问题