angular 5 自定義表單驗證

本文參考地址:連接javascript

第三方UI組件:Ant-Designhtml

近期在作angular的表單,目前項目上已經升級到angular 5了,須要作一些自定義表單驗證,用戶輸入的是在服務器上的絕對路徑,因此要驗證是不是以「/」開頭java

表單驗證 (Validator) 的本質上是一個function,感受跟pipe 思路相似typescript

html:服務器

<form nz-form [formGroup]="configForm" (ngSubmit)="submitConfig()" (ngReset)="resetConfig()">
    <div nz-form-item nz-row>
            <div nz-form-label nz-col [nzSpan]="6">
              <label nz-form-item-required>數據存儲目錄</label>
            </div>
            <div nz-form-control nz-col [nzSpan]="12" nzHasFeedback>
              <nz-input formControlName="NODE_PATH" [nzPlaceHolder]="'存儲路徑'" [nzSize]="'large'">
                <ng-template #addOnBefore>{{ filePathPrefix }}</ng-template>
              </nz-input>
              <div nz-form-explain *ngIf="validateCorrect('NODE_PATH')">
                只支持一個目錄,好比:/home/temp/data
              </div>
              <div nz-form-explain *ngIf="validateError('NODE_PATH')">
                存儲目錄不可爲空
              </div>
              <div nz-form-explain *ngIf="getFormControl('NODE_PATH').hasError('invalidPath')">
                絕對路徑必需要以「/」開頭
              </div>
            </div>
    </div>
</form>

typescript:異步

export class ConfigComponent implements OnInit {

  configForm : FormGroup;
  filePathPrefix = 'file://';

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.configForm = this.fb.group({
      NODE_PATH: [null, Validators.required, ConfigComponent.validateFilePath]
    });
  
  }

  static validateFilePath(control: FormControl) {
    let filePath = control.value;
    return Observable.of(filePath && filePath.startsWith('/')).map(result => {
      return !!result ? null : { invalidPath: true };
    });
  }


  /**
   * 提交配置信息
   */
  submitConfig() {
    
  }

  /**
   * 從新配置信息
   */
  resetConfig() {
    
  }

  getFormControl(name) {
    return this.configForm.controls[name];
  }

}

validators 必需要返回一個Observable 對象,由於是異步驗證ui

當用戶輸入是以「/」開頭時,返回null,表示驗證經過this

當用戶輸入沒有以「/」開頭時,返回一個對象,表示驗證失敗,返回對象能夠自定義,好比這裏就返回了一個對象 { invalidPath: true } ,這樣的話就能夠在html 裏使用hasError('invalidPath') 來取值了spa

這樣寫其實html 冗餘代碼比較多,能夠把各類提示信息再封裝一下,讓html 更加簡潔,可讀性更強code

相關文章
相關標籤/搜索