Angular 2-用于警告/提示的表单验证 [英] Angular 2 - Form validation for warnings/hints

查看:60
本文介绍了Angular 2-用于警告/提示的表单验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加不会使表单无效的表单验证.验证仅应显示为警告.

I'm trying to add form validations which don't invalidate the form. The validation should only appear as warnings.

例如年龄验证.年龄大于90表示警告,而年龄大于120表示错误.

E.g. an age validation. An age greater than 90 shows a warning and an age greater than 120 shows an error.

我已经尝试过在表单上使用两个FormGroup,在输入字段上使用两个[formControl].仅使用第一个[formControl].

I've tried it with two FormGroups on a form and two [formControl]s on the input field. Only the first [formControl] is used.

是否可以将Angulars表单验证用于这种验证?哪种方法走?

Is it possible to use Angulars form validation for this kind of validation? Which approach is the way to go?

推荐答案

我已通过创建自定义验证程序来完成此操作,该验证程序始终返回null.此外,此验证器还会创建其他属性warnings.然后只需从您的视图中简单地检查该属性即可.

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: `
    <div [formGroup]="form">
      Age: <input formControlName="age"/>
      <div *ngIf="age.errors?.required" [hidden]="age.pristine">
      Error! Age is required
      </div>
      <div *ngIf="age.errors?.impossibleAge" [hidden]="age.pristine">
      Error! Age is greater then 120
      </div>
      <div *ngIf="age.warnings?.tooBigAge" [hidden]="age.pristine">
      Warning! Age is greater then 90
      </div>
      <p><button type=button [disabled]="!form.valid">Send</button>
    </div>
  `,
})
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");
  }
}

示例: https://plnkr.co/edit/me0pHePkcM5xPQ7nzJwZ?p=preview

这篇关于Angular 2-用于警告/提示的表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆