angular6 表單驗證


這里使用的是模型驅動的表單

1、app.module.ts

import { ReactiveFormsModule } from '@angular/forms';
 
@NgModule({
  ...
  imports: [ReactiveFormsModule, ...],
  ...
})
export class AppModule{
}

文件中加入了ReactiveFormsModule模塊,它是使用模型驅動表單所必須的。

 

2、app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  name: string
  score: number;
  formData: any;

  constructor() { }

  ngOnInit() {
    this.formData = new FormGroup({
      name: new FormControl(this.name, Validators.compose([
        Validators.required,
      ])),
      score: new FormControl(this.score, Validators.compose([
        Validators.required,
        this.scoreValueValidator
      ]))
    });
  }

  scoreValueValidator(control: FormControl): any {
    if (control.value < 0 || control.value > 100) {
      return { value: {info: '分數必須大於等於0,小於等於100'} };
    }
  }

  onsubmit(data: any) {
    this.name= data.name;
    this.score = data.score
  }

}

表單驗證,可以使用內置的表單驗證,也可以使用自定義驗證方法。

(1)  內置表單驗證。

Validators是angular內置的驗證器模塊,可以使用它實現強制字段、最小長度、最大長度和模式等,我這里設置了name和score是強制字段,當然,你可以加入Validators.minLength(6), Validators.maxLength(10),Validators.pattern("[^ @]*@[^ @]*")等等

(2)  自定義表單驗證。

scoreValueValidator是自定義的驗證方法,用於驗證分數是否大於等於0,小於等於100,傳遞的參數是當前需要驗證的表單的FormControl,通過control.value可以拿到輸入的分數值。

 

3、app.component.html

<div class="container">
  <form [formGroup] = "formData" (ngSubmit) = "onsubmit(formData.value)">
    <div class="form-group">
      <label for="name">姓名</label>
      <em>*</em>
      <input type="text" class="form-control" formControlName="name" id="name">
      <div [hidden]="formData.get('name').valid || formData.get('name').untouched" class="small">
        <p [hidden]="!formData.hasError('required', 'threshold')">必填項</p>
      </div>
    </div>
    <div class="form-group">
      <label for="score">分數</label>
      <em>*</em>
      <input type="number" min="0" max="100" class="form-control" formControlName="score" id="score">
      <div [hidden]="formData.get('score').valid || formData.get('score').untouched" class="small">
        <p [hidden]="!formData.hasError('required', 'score')">必填項</p>
        <p [hidden]="!formData.hasError('value', 'score')">{{formData.getError('value', 'score')?.info}}</p>
      </div>
    <button type="submit" [disabled]="!formData.valid" class="btn btn-sm btn-primary">提交</button>
  </form>
</div>

頁面中顯示錯誤信息

對於提交按鈕,我們已經在方括號中添加了disabled,它被賦予值 !formData.valid。因此,如果formData.valid無效,按鈕將保持禁用狀態,用戶將無法提交它。

 

4、app.component.css

em {
    color:red;
    margin-left: 0.25em
}
.ng-touched:not(form),.ng-invalid:not(form) {
    border: 1px solid #f00;
}
.ng-valid:not(form),.ng-untouched:not(form) {
    border: 1px solid #ddd;
}
p{
    color:#f00;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM