在Angular2表单中应用验证器

时间:2016-07-07 08:58:56

标签: angular angular2-forms

所以我的问题非常简单。当表单从ngModel中获取其值时,如何在表单上应用验证器。

所以这是我的组成部分:

constructor(private _fb ? : FormBuilder,
  private _router ? : Router,
  private _usersService ? : UsersService,
  private _route ? : ActivatedRoute) {}


ngOnInit() {
  // Fetch the Id when Editing the User
  this.sub = this._route.params.subscribe(params => {
    let id = params['id'];
    this.title = id ? "Edit User" : "New User";
    if (!id)
      return;

    this._usersService.getUser(id)
      .subscribe(
        user => this.user = user,
        response => {
          if (response.status == 404)
            this._router.navigateByUrl("/NotFound");
        }
      )
  });
}

ngAfterContentInit() {
  // Let's define the form group
  this.form = this._fb.group({
    name: ['', Validators.compose(
      [Validators.required, Name.cannotContainSpace]
    ), Name.shouldBeUnique],
    email: ['', Validators.compose(
      [Validators.required, Email.shouldBeAnEmail]
    )],
    phone: ['', Validators.compose(
      [Validators.pattern("[0-9]{5,10}"), Validators.required]
    )],
  });
}

ngAfterViewInit() {
  // Component views are initialized
  // I probably could Apply my validators in this hook cycle.
}

ngOnDestroy() {
  this.sub.unsubscribe();
}
<!-- Just put an example for the form-control -->
<input [(ngModel)]="user.name" type="text" class="form-control" id="inputName" placeholder="Name" ngControl="name" #name="ngForm">
<div *ngIf="name.control.pending">
  searching for uniqueness...
  <i class="fa fa-spinner fa-spin fa-1x"></i>
</div>
<div *ngIf="name.touched && name.errors">
  <div *ngIf="name.errors.required" class="alert alert-danger">Name is required</div>
  <div *ngIf="name.errors.cannotContainSpace" class="alert alert-danger">Name cannot contain space</div>
  <div *ngIf="name.errors.shouldBeUnique" class="alert alert-danger">Name should be unique</div>
</div>

因此,当它加载视图时,我得到了用户的表单集,但Validator不会等待在检查之前设置新值!

1 个答案:

答案 0 :(得分:0)

问题在于control.touched条件检查。尝试这样的事情:

<div *ngIf="name.valid">
  <div *ngIf="name.hasError('required')" class="alert alert-danger">Name is required</div>
  <div *ngIf="name.hasError('cannotContainSpace')" class="alert alert-danger">Name cannot contain space</div>
  <div *ngIf="name.hasError('shouldBeUnique')" class="alert alert-danger">Name should be unique</div>
</div>