溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2021-08-02 11:27:35 來源:億速云 閱讀:134 作者:小新 欄目:web開發(fā)

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

一、使用響應(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:顯示錯誤
     */
    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="請輸入用戶名" class="form-control" id="username" formControlName="username" />
  </div>
  <div class="form-group">
    <label for="mobile">手機號碼:</label>
    <input type="text" placeholder="請輸入手機號碼" class="form-control" id="mobile" formControlName="mobile"/>
  </div>
  <div formGroupName="password" >
    <div class="form-group">
      <label>密碼:</label>
      <input type="password" class="form-control" placeholder="請輸入密碼" formControlName="pass1" />
    </div>
    <div class="form-group">
      <label>確認(rèn)密碼:</label>
      <input type="password" class="form-control" placeholder="請再次輸入密碼" formControlName="pass2" />
    </div>
  </div>
  <div class="form-group">
    <input type="submit" value="提交" class="btn btn-warning" [disabled]="!myForm.valid" />
  </div>
</form>

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

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

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

}

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

三、自定義一個校驗方法的步驟

1、把項目中需要用的校驗器單獨寫一個文件

import { FormControl, FormGroup } from '@angular/forms';
/**
 * 自定義驗證器(其實就是一個函數(shù),一個返回任意對象的函數(shù))
 * 傳遞的參數(shù)是當(dāng)前需要驗證的表單的FormControl
 * 通過傳遞的參數(shù)獲取當(dāng)前表單輸入的值
 */
export function mobileValidator(control: FormControl): any {
  console.dir(control);
  // 獲取到輸入框的值
  const val = control.value;
  // 手機號碼正則
  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: '手機號碼格式不正確' } };
}

2、使用自己定義的校驗器

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、定義一個密碼組的校驗

// 定義一個密碼組的驗證方法
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)于前端頁面中錯誤的顯示

1、頁面顯示錯誤

<div class="form-group">
  <label for="username">用戶名:</label>
  <input type="text" placeholder="請輸入用戶名" class="form-control" id="username" formControlName="username" />
  <!-- 當(dāng)輸入框沒有訪問的時候或者合法的時候不顯示 -->
  <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">手機號碼:</label>
  <input type="text" placeholder="請輸入手機號碼" 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="請輸入密碼" formControlName="pass1" />
  </div>
  <div class="form-group">
    <label>確認(rèn)密碼:</label>
    <input type="password" class="form-control" placeholder="請再次輸入密碼" formControlName="pass2" />
  </div>
  <!-- 對于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顯示錯誤

1、在input輸入框上寫上

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

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

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

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI