angular4響應式表單與校驗
阿新 • • 發佈:2018-11-16
html檔案:
<form [formGroup]="formModel" (submit)="onSubmit()">
<h2>響應式表單與校驗</h2>
<div><label>使用者名稱:</label><input type="text" formControlName="username"/></div>
<div [hidden]='!formModel.hasError("required","username")'>使用者名稱是必填項</div>
<!-- required不是校驗器的名字,而是失敗後返回的物件裡的key值
* 只要是required有值就認為是錯誤的,不論是什麼值true或者是物件
* username是想要檢查的欄位名字
-->
<div [hidden]='!formModel.hasError("minlength","username")'>使用者名稱的最小長度是6</div>
<div><label>手機號:</label><input type="text" formControlName="mobile" /></div>
<div [hidden]='!formModel.hasError("mobile","mobile")'>手機號不合法</div>
<div formGroupName="passwordsGroup">
<div><label>密碼:</label><input type="password" formControlName="password"/></div>
<div [hidden]='!formModel.hasError("minlength",["passwordsGroup","password"])' >密碼的最小長度是6</div>
<!-- 這裡注意想要校驗的欄位的寫法是一個數組 -->
<div><label>確認密碼:</label><input type="password" formControlName="pwconfrim"/></div>
<div [hidden]='!formModel.hasError("equal","passwordsGroup")'>
{{formModel.getError('equal','passwordsGroup')?.descx}}
<!-- 可以在校驗器中的key值中定義提示語 -->
</div>
</div>
<button type="submit">註冊</button>
</form>
<div>
{{formModel.status}}
</div>
ts檔案:
import { Component,OnInit } from '@angular/core';
import { FormGroup,FormControl,FormBuilder,AbstractControl,Validators } from '@angular/forms';
import { validators } from './validator/validators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
//校驗器就是一個普通的方法,名字隨意定,接收一個引數,引數的型別必須是AbstractControl的型別,必須有返回值,返回值的//可以是任意結果的一個物件,物件要求key必須是string型別的,值可以是任意型別的
// xxxx(control:AbstractControl):{[key:string]:any} {
// return null;
// }
//校驗器可以單獨的提取出去,寫在validators.ts檔案中
public val:validators;//定義一個validators型別的變數 val
formModel: FormGroup;
// constructor(){
// this.formModel = new FormGroup({
// username: new FormControl(),
// moblie: new FormControl(),
// passwordsGroup: new FormGroup({
// password: new FormControl(),
// pwconfrim: new FormControl()
// })
// });
// }
//同上的功能
//FormBuilder的group方法可以再接收一個額外的方法來做校驗,用“,”分開
//['',,]第一個元素是一個初始值,第二個元素是一個校驗方法,第三個元素是非同步校驗方法
constructor(fb:FormBuilder){
this.val = new validators();
this.formModel =fb.group({
username: ['',[Validators.required,Validators.minLength(6)]],//['']例項化了一個FormControl,Validators內建表單校驗都儲存在這裡
mobile: ['',this.val.mobileValidator,this.val.mobileAsyncValidator],
passwordsGroup: fb.group({
password: ['',Validators.minLength(6)],
pwconfrim: ['']
},{validator :this.val.euqalValidator})
});
}
onSubmit() {
// let isValid: boolean = this.formModel.get("username").valid;
//符合所有校驗規則後,isValid就是true;
// console.log("username的校驗結果是"+isValid);
// let errors:any = this.formModel.get("username").errors;
// console.log("username的錯誤資訊是"+JSON.stringify(errors))
if(this.formModel.valid){ //所有表單都合法才打印表單的值
console.log(this.formModel.value);
}
}
ngOnInit() {
}
}
校驗檔案validators.ts
import { FormControl,FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
export class validators{
mobileValidator(control:FormControl):any {
let myReg = /^1(3|4|5|7|8)+\d{9}$/;
let valid = myReg.test(control.value);
console.log("moblie的校驗結果是"+valid)
return valid ? null : {mobile:true};//如果valid是true 返回是null
}
//非同步校驗器,返回的不是物件,而是一個非同步校驗流
mobileAsyncValidator(control:FormControl):any {
let myReg = /^1(3|4|5|7|8)+\d{9}$/;
let valid = myReg.test(control.value);
console.log("moblie的校驗結果是"+valid)
return Observable.of(
valid ? null : {mobile:true}
).delay(5000)//延遲5秒
}
euqalValidator(group:FormGroup):any {
let password :FormControl = group.get("password") as FormControl;
let pwconfrim :FormControl = group.get("pwconfrim") as FormControl;
let valid :boolean = (password.value === pwconfrim.value);
console.log("密碼校驗結果是"+valid);
return valid ? null : {equal:{descx:"密碼和確認密碼不匹配"}};
}
}