Angular-没有表单标签的表单验证

时间:2018-09-05 11:53:48

标签: html angular forms

我正在尝试完成注册表。我必须不使用表单标签来做到这一点。

我有此注册表:

<div class="row">
    <div class="center col-xs-8 col-xs-offset-2">

        <p class="h5 text-center mb-4">{{ 'Signup' | translate }}</p>

        <div class="form-group">
            <label for="email">{{ 'SignupEmail' | translate }}</label>
                <input type="text" [(ngModel)]="user.email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
                <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
                    <div *ngIf="f.email.errors.required">Email is required</div>
                    <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
                </div>
            </div>
            <div class="form-group">
                <label for="username">{{ 'SignupUsername' | translate }}</label>
                <input type="text"  [(ngModel)]="user.name" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
            </div>
            <div class="form-group">
                <label for="password">{{ 'SignupPassword' | translate }}</label>
                <input type="password"  [(ngModel)]="user.password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
            </div>
            <div class="form-group">
                <label for="birth">{{ 'SignupBirth' | translate }}</label>
                <input type="date"  [(ngModel)]="user.dateNaissance" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
            </div>
            <div class="form-group">
                <button [disabled]="loading" class="btn btn-info" (click)="onSubmit()" >{{ 'SignupSubmit' | translate }}</button>
                <img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
                <div class="text-center">
                  {{ 'SignupAccount1' | translate }} <a routerLink="/login">{{ 'SignupAccount2' | translate }}</a>
                </div>
            </div>
        </div>
    </div>

问题是,即使我在输入中输入了正确的地址邮件,也总是需要邮件和其他输入。而且我不明白为什么...

这是 register.component.ts

import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {first} from 'rxjs/operators';
import {Router} from '@angular/router';
import {AlertService} from '../services/alert.service';
import {UserService} from '../services/user.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.sass']
})
export class RegisterComponent implements OnInit {

  registerForm: FormGroup;
  loading = false;
  submitted = false;
  user: any;


  constructor(private fb: FormBuilder, private router: Router, private userService: UserService, private alertService: AlertService) {

  }

  ngOnInit() {
    this.registerForm = this.fb.group({
      username: ['', Validators.required],
      //gender: ['', Validators.required],
      birth: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8)]]
    });

    this.user = new Object();

  }

  click(ev) {
    console.log(ev.target.defaultValue);
  }

  // convenience getter for easy access to form fields
  get f() {return this.registerForm.controls;}

  onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.registerForm.invalid) {
      window.alert("Informations invalides");
      return;
    }

    this.loading = true;
    this.userService.register(this.registerForm.value)
      .pipe(first())
      .subscribe(
      data => {
        this.alertService.success('Registration successful', true);
        this.router.navigate(['/login']);
      },
      error => {
        this.alertService.error(error);
        this.loading = false;
      });
  }

}

您能帮我验证此表单吗(但不添加表单标签)...

谢谢!

1 个答案:

答案 0 :(得分:2)

您使用了反应形式,因此在div中使用[formGroup],在该div中使用formControlName进行验证。

在这里,我创建了一个带有验证且没有form标签的反应形式演示。

Stackblitz Demo without Form Tag