Angular 2中的表单输入验证(模板驱动)

时间:2016-12-14 17:45:13

标签: angular

我想让这些输入显示一条消息,例如"姓名是必需的"提交时(所以提交按钮被禁用,直到里面有名字)。使用Angular 2模板驱动表单可能有一种简单的方法吗?我想我应该在表单的HTML中提供一些属性,并将它连接到一个组件,但是在跟踪文档中的示例时无法弄清楚。感谢所有帮助。

<form class="">
    <div>
        <p>Name:</p>
        <input type="text">
    </div>
    <div class="link-input">
        <p>City:</p>
        <input type="text">
    </div>

    <button 
        (click)="submitForm()">
        Submit
    </button>
</form>

4 个答案:

答案 0 :(得分:3)

你的Html:

<form role="form" [formGroup]="inputForm" novalidate>
    <div>
        <p>Name:</p>
        <input
         formControlName="name"
         type="text">
    </div>
    <div class="link-input">
        <p>City:</p>
        <input
         formControlName="city"
         type="text">
    </div>

    <button 
        [disabled]="!inputForm.valid"
        (click)="submitForm()">
    </button>
</form>

你的组件:

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

export class InputComponent  {   
   public inputForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {

  this.inputForm = this.formBuilder.group({
  name:    new FormControl('', Validators.required),
  city:    new FormControl('', Validators.required),
   });
  }
//... codes..
}

答案 1 :(得分:3)

模板驱动形式

我也有这个问题,我找到了答案,我想和你分享。 我创建了一个带有验证的登录表单,如下所示:

login.component.html

<div class="col-md-6 col-md-offset-3">
    <h2>Login</h2>
    <form name="form" (ngSubmit)="f.form.valid && login()" #f="ngForm" novalidate>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
            <label for="username">Username</label>
            <input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required />
            <div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div>
        </div>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
            <label for="password">Password</label>
            <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required />
            <div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div>
        </div>
        <div class="form-group">
            <button [disabled]="loading" class="btn btn-primary">Login</button>
            <img *ngIf="loading" src="loading.gif" />
            <a [routerLink]="['/register']" class="btn btn-link">Register</a>
        </div>
    </form>
</div>

login.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { AlertService, AuthenticationService } from '../services';

@Component({
    templateUrl: './login.component.html'
})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService,
        private alertService: AlertService) { }

    ngOnInit() {}

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
                data => {
                    this.router.navigate([this.returnUrl]);
                },
                error => {
                    this.alertService.error(error);
                    this.loading = false;
                });
    }
}

如果您需要任何帮助,我希望这会对您有所帮助。我很乐意帮助你。 @Smithy我也在学习角度2。

答案 2 :(得分:2)

这确保表格已被触摸(输入已更改)且名称字段长度至少为1个字母。你可以为城市做类似的事情。

组件:

import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';

export class InputComponent  {   
  public inputForm: FormGroup;
  constructor(private formBuilder: FormBuilder) {

    this.inputForm = this.formBuilder.group({
      name:    new FormControl('', Validators.required, Validators.minLength(1)]),
      city:    new FormControl('', Validators.required),
    });
  }
}

查看:

<form [formGroup]="inputForm" novalidate>
  <p>Name:</p>
  <input placeholder="Exercise" formControlName="name">
  <div class="errorMsg" *ngIf="inputForm.get('name').touched && inputForm.get('name').status === 'INVALID'">
    Name is required</div>
  <p>City:</p>
  <input placeholder="Exercise" formControlName="city">
  <button [disabled]="!inputForm.valid || !inputForm.touched (click)="submitForm()">Submit</button>
</form>

答案 3 :(得分:2)

角度2形式验证与我们在角度1中所做的完全不同。 当你将表格标签写入DOM时,角度2将ngForm和ngControl添加到它。 可以使用angular2属性[禁用]禁用按钮。要保持按钮禁用,您需要将验证属性应用于[已禁用]。我给出了一个简单的例子,它将为您提供表单验证,输入字段验证和模式验证。 该表格有效后,该按钮将被禁用

在您的HTML中

<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)">
  <div class="form-group" [ngClass]="{'has-error':!signinForm.controls['usermail'].valid && signinForm.controls['usermail'].touched}">
      <label>Email Address</label>
      <input class="form-control" type="email" [formControl]="signinForm.controls['usermail']">
      <span *ngIf="signinForm.controls['usermail'].hasError('required') && signinForm.controls['usermail'].touched && !signinForm.submitted" class="required pull-right">*Please Enter Email</span>
      <span *ngIf="signinForm.controls['usermail'].hasError('pattern') && signinForm.controls['usermail'].touched" class="required pull-right">*Invalid Email</span>
    </div>
    <div class="form-group" [ngClass]="{'has-error':!signinForm.controls['userpass'].valid && signinForm.controls['userpass'].touched}">
       <label>Password</label>
       <input class="form-control" type="password" [formControl]="signinForm.controls['userpass']" (focus)="showErrorMessage=false">
        <span *ngIf="signinForm.controls['userpass'].hasError('required') && signinForm.controls['userpass'].touched && !signinForm.submitted" class="required pull-right">*Please Enter Password</span>
    </div>
      <button type="submit" class="btn btn-pri mds_btn" [disabled]="!signinForm.valid">Login</button>       
</form>

在您的组件

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: [ './login.component.scss' ]
})
export class LoginComponent {
   myForm: FormGroup;

   emailRegex: any = '^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$';
    passRegex:any ='^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$'; 

   constructor(fb: FormBuilder) {

      this.myForm = fb.group({
         'logmail': [ null, Validators.compose([ Validators.required, Validators.pattern(this.emailRegex) ]) ],
         'logpass': [ null, Validators.compose([ Validators.required, Validators.pattern(this.passRegex) ]) ]
      });

    this.myForm.valueChanges.subscribe((form: any) => {
   });
  }

  submitForm(lgvalue: any) {
       //do logic here after submitting the form

  }
}

在这个例子中,我正在使用FormBuilder的FormGroup指令.FormBuilder创建FormGroup的实例,我们将其称为表单。我也订阅了表单,这样只要在输入字段中输入值,就会订阅表单。

我希望这会对你有所帮助:)。