angular4中關(guān)于表單校驗(yàn)的示例分析

這篇文章給大家分享的是有關(guān)angular4中關(guān)于表單校驗(yàn)的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)建站是一家專業(yè)提供西鄉(xiāng)塘企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站、成都外貿(mào)網(wǎng)站建設(shè)公司、H5開發(fā)、小程序制作等業(yè)務(wù)。10年已為西鄉(xiāng)塘眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。

一、使用響應(yīng)式表單的步驟

1、在模塊(一般是app.module.ts)中引入ReactiveFormsModule
2、在組件的ts文件中使用響應(yīng)式表單

import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
export class ReactiveFormComponent implements OnInit {
  private myForm: FormGroup;
  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  ngOnInit() {
  }
  // 創(chuàng)建表單元素
  createForm() {
    this.myForm = this.fb.group({
      username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(6)]],
      mobile: ['', [Validators.required]],
      password: this.fb.group({
        pass1: [''],
        pass2: ['']
      })
    });
  }
  // 提交表單函數(shù)
  postDate() {
    /**
     * valid:是否有效
     * invalid:無效
     * dirty:臟
     * status:狀態(tài)
     * errors:顯示錯(cuò)誤
     */
    if(this.myForm.valid){
      console.log(this.myForm.value);
    }
  }
}

3、在組件的html頁面中使用

<form [formGroup]="myForm" (ngSubmit)="postDate()">
  <div class="form-group">
    <label for="username">用戶名:</label>
    <input type="text" placeholder="請(qǐng)輸入用戶名" class="form-control" id="username" formControlName="username" />
  </div>
  <div class="form-group">
    <label for="mobile">手機(jī)號(hào)碼:</label>
    <input type="text" placeholder="請(qǐng)輸入手機(jī)號(hào)碼" class="form-control" id="mobile" formControlName="mobile"/>
  </div>
  <div formGroupName="password" >
    <div class="form-group">
      <label>密碼:</label>
      <input type="password" class="form-control" placeholder="請(qǐng)輸入密碼" formControlName="pass1" />
    </div>
    <div class="form-group">
      <label>確認(rèn)密碼:</label>
      <input type="password" class="form-control" placeholder="請(qǐng)?jiān)俅屋斎朊艽a" formControlName="pass2" />
    </div>
  </div>
  <div class="form-group">
    <input type="submit" value="提交" class="btn btn-warning" [disabled]="!myForm.valid" />
  </div>
</form>

二、使用表單校驗(yàn)數(shù)據(jù)

1、angular中自帶了三個(gè)常見的表單校驗(yàn)的是在Validators中的required,minLength,maxLength
2、自定義表單校驗(yàn)器(其實(shí)就一個(gè)函數(shù),函數(shù)的參數(shù)是當(dāng)前需要校驗(yàn)的行,返回一個(gè)任意對(duì)象)

**格式**
export function fnName(control:FormControl|FormGroup):any{

}

3、響應(yīng)式表單字段中可以寫三個(gè)值,第一個(gè)是返顯到頁面上的,第二個(gè)參數(shù)是校驗(yàn)器(可以是一組),第三個(gè)參數(shù)異步校驗(yàn)(常見判斷手機(jī)號(hào)碼,用戶名是否重復(fù)注冊(cè))

三、自定義一個(gè)校驗(yàn)方法的步驟

1、把項(xiàng)目中需要用的校驗(yàn)器單獨(dú)寫一個(gè)文件

import { FormControl, FormGroup } from '@angular/forms';
/**
 * 自定義驗(yàn)證器(其實(shí)就是一個(gè)函數(shù),一個(gè)返回任意對(duì)象的函數(shù))
 * 傳遞的參數(shù)是當(dāng)前需要驗(yàn)證的表單的FormControl
 * 通過傳遞的參數(shù)獲取當(dāng)前表單輸入的值
 */
export function mobileValidator(control: FormControl): any {
  console.dir(control);
  // 獲取到輸入框的值
  const val = control.value;
  // 手機(jī)號(hào)碼正則
  const mobieReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
  const result = mobieReg.test(val);
  return result ? null : { mobile: { info: '手機(jī)號(hào)碼格式不正確' } };
}

2、使用自己定義的校驗(yàn)器

createForm() {
  this.myForm = this.fb.group({
    username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(6)]],
    mobile: ['', [Validators.required, mobileValidator]],
    password: this.fb.group({
      pass1: [''],
      pass2: ['']
    })
  });
}

3、定義一個(gè)密碼組的校驗(yàn)

// 定義一個(gè)密碼組的驗(yàn)證方法
export function passValidator(controlGroup: FormGroup): any {
  // 獲取密碼輸入框的值
  const pass1 = controlGroup.get('pass1').value as FormControl;
  const pass2 = controlGroup.get('pass2').value as FormControl;
  console.log('你輸入的值:', pass1, pass2);
  const isEqule: boolean = (pass1 === pass2);
  return isEqule ? null : { passValidator: { info: '兩次密碼不一致' } };
}

4、使用

createForm() {
  this.myForm = this.fb.group({
    username: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(6)]],
    mobile: ['', [Validators.required, mobileValidator]],
    password: this.fb.group({
      pass1: [''],
      pass2: ['']
    }, {validator: passValidator})
  });
}

四、關(guān)于前端頁面中錯(cuò)誤的顯示

1、頁面顯示錯(cuò)誤

<div class="form-group">
  <label for="username">用戶名:</label>
  <input type="text" placeholder="請(qǐng)輸入用戶名" class="form-control" id="username" formControlName="username" />
  <!-- 當(dāng)輸入框沒有訪問的時(shí)候或者合法的時(shí)候不顯示 -->
  <div [hidden]="myForm.get('username').valid || myForm.get('username').untouched">
    <p [hidden]="!myForm.hasError('required','username')">用戶名必填的</p>
    <p [hidden]="!myForm.hasError('minlength','username')">用戶名長度過短</p>
    <p [hidden]="!myForm.hasError('maxlength','username')">用戶名長度太長</p>
  </div>
</div>
<div class="form-group">
  <label for="mobile">手機(jī)號(hào)碼:</label>
  <input type="text" placeholder="請(qǐng)輸入手機(jī)號(hào)碼" class="form-control" id="mobile" formControlName="mobile"/>
  <div [hidden]="myForm.get('mobile').valid || myForm.get('mobile').untouched">
    <p [hidden]="!myForm.hasError('mobile', 'mobile')">{{myForm.getError('mobile', 'mobile')?.info}}</p>
  </div>
</div>
<div formGroupName="password" >
  <div class="form-group">
    <label>密碼:</label>
    <input type="password" class="form-control" placeholder="請(qǐng)輸入密碼" formControlName="pass1" />
  </div>
  <div class="form-group">
    <label>確認(rèn)密碼:</label>
    <input type="password" class="form-control" placeholder="請(qǐng)?jiān)俅屋斎朊艽a" formControlName="pass2" />
  </div>
  <!-- 對(duì)于group可以不在外面加一層判斷 -->
  <div>
    <p [hidden]="!myForm.hasError('passValidator','password')">
      {{myForm.getError('passValidator','password')?.info}}
    </p>
  </div>
</div>

2、定義樣式文件

.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;
}

五、自定義class顯示錯(cuò)誤

1、在input輸入框上寫上

表示該字段無效且觸碰過就添加這個(gè)class=”error”

 [class.error]="myForm.get('username').invalid && myForm.get('username').touched"

感謝各位的閱讀!關(guān)于“angular4中關(guān)于表單校驗(yàn)的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

分享名稱:angular4中關(guān)于表單校驗(yàn)的示例分析
當(dāng)前URL:http://muchs.cn/article2/ihdhic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、網(wǎng)頁設(shè)計(jì)公司網(wǎng)站維護(hù)、外貿(mào)網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)、網(wǎng)站營銷

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名