2016-12-05 34 views
3

我創建使用驗證檢查的形式,檢查表單驗證當用戶填寫表單角2

import { FormGroup, Validators, FormControl } from "@angular/forms"; 

目前我有Submit button[disabled]直到表格填寫正確。如果表單有效或無效,我向用戶顯示的唯一方法是在表單字段無效時在輸入中顯示紅色。

enter image description here

我想顯示錯誤信息給用戶向他們展示什麼是錯的。

是否有內置Angular2顯示錯誤消息或爲什麼輸入字段無效?或者我需要爲每個表單字段構建自定義錯誤消息?如果是這樣,我將如何去檢查每個輸入字段,讓我們說,當有人離開各自領域的焦點。因此,如果他們離開輸入字段並且無效,那麼我可以顯示一條消息,告訴他們這是無效的,爲什麼?

我有一個方法來顯示消息,我只需要想出一個方法來獲取和錯誤消息。換句話說,從表單中生成文本,說明爲什麼它無效。

Please provide a valid mobile number 

代碼

REGEX

ngOnInit() { 
     this.personalForm = new FormGroup({ 
      email : new FormControl(this.auth.user.email,Validators.required), 
      first_name: new FormControl(null,[ 
       Validators.required, 
       Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$") 
      ]), 
      middle_name: new FormControl(null,[ 
       Validators.required, 
       Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$") 
      ]), 

      last_name: new FormControl(null,[ 
       Validators.required, 
       Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$") 
      ]), 

      dob : new FormControl (null, [ 
       Validators.required, 
       Validators.pattern("[1][9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[2][0][0-9][0-9]-[0-9][0-9]-[0-9][0-9]") 
      ]), 
      mobile_phone: new FormControl(null, [ 
       Validators.required, 
       Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]") 
      ]), 
      home_phone: new FormControl(null, [ 
       Validators.required, 
       Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]") 
      ]), 

      business_phone: new FormControl(null, [ 
       Validators.required, 
       Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]") 
      ]), 
      fax_number: new FormControl(null, [ 
       Validators.required, 
       Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]") 
      ]), 
      ssn: new FormControl(null, [ 
       Validators.required, 
       Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]") 
      ]) 
     }); 
    } 

有效的布爾/處理表單數據

save(model: Personal, isValid: boolean) { 
     if (!isValid) { 
      console.log('Personal Form is not valid'); 
      console.log(model, isValid); 
     } else { 
      console.log('Personal Form is valid'); 
      console.log(model, isValid); 
      let headers = new Headers(); 
      headers.append('Content-Type', 'application/json'); 
      return this.http 
       .post('http://localhost:4200/api/updateProfile', 
        model, 
        {headers: headers}) 
       .map((res: Response) => res.json()) 
       .subscribe((res) => { 
        //do something with the response here 
        console.log(res); 
       }); 
     } 
    } 

<form [formGroup]="personalForm" novalidate (ngSubmit)="save(personalForm.value, personalForm.valid)"> 
    <div class="row"> 
     <div class="col-sm-12 col-md-12 col-lg-12"> 
      <div class="card card-inverse card-success"> 
       <div class="card-header"> 
        <strong>Personal Information</strong> 
       </div> 
       <div class="card-block"> 
        <div class="row"> 
         <div class="form-group col-sm-12 col-md-12"> 
          <label for="email">Email</label> 
          <div class="input-group"> 
           <span class="input-group-addon"><i class="fa fa-envelope"></i> 
      </span> 
           <input type="text" class="form-control" id="email" formControlName="email" placeholder="{{personal.email}}"readonly> 
          </div> 
          <div class="alert alert-danger" *ngIf="!personalForm.controls.email.valid && submitted "> 
           *Email is required. 
          </div> 
         </div> 
        </div> 
+0

這可以全部在HTML模板中處理。你可以請張貼你的表格模板。 – Brad

+0

我添加了一張表格,所以你可以se.e – wuno

+0

我想我看我怎麼能控制這個知道自定義錯誤。但是我可以從形式中獲得最多的信息。我想節省自己的時間。請參閱這一行!personalForm.controls.middle_name.valid &&提交請注意這些控件。這是內置到FormControl?所以我可以調用我構建的FormControls中的每個對象?我正確地做對了嗎? – wuno

回答

0

摘要

要訪問FormGroupinput字段,你可以使用syntax訪問controls已創建。

this.FormGroupName.get('ControlName').status 

,將返回VALIDINVALID

在我而言,這是它是怎麼做,

導入正確的包,

import {FormGroup, Validators, FormControl } from "@angular/forms"; 
import {INVALID, VALID} from "@angular/forms/src/model"; 

創建FormGroup

personalForm: FormGroup; 

創建FormControl

ngOnInit() { 
     this.personalForm = new FormGroup({ 
      first_name: new FormControl(null,[ 
       Validators.required, 
       Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$") 
      ]), 
    }); 
} 

添加FormControlNameformfunction打電話時你想要的error進行檢查。

<input (blur)="firstNameValidate('*First Name Required', 'Use 1-30 letters to spell your name.')" type="text" class="form-control" placeholder="Enter first name" id="first_name" formControlName="first_name"> 

檢查VALIDINVALID

firstNameValidate(ErrorTitle, ErrorMessage) { 
     if (this.personalForm.get('first_name').status == VALID) { 
      this.getSuccess("First Name Entered", "First name entered correctly"); 
     } else { 
      this.toastWarning(ErrorTitle, ErrorMessage); 
     } 
    } 

調用錯誤

在我的情況,我決定顯示一個toast我的錯誤。所以我用blur跟蹤用戶何時離開input字段。當用戶移出input字段時,firstNameValidate()函數被調用,並且基於值VALIDINVALID顯示正確的toast。根據response這兩個functions中的一個被解僱。

toastWarning(ErrorTitle, ErrorMessage) { 
     var toastOptions:ToastOptions = { 
      title: ErrorTitle, 
      msg: ErrorMessage, 
      showClose: true, 
      timeout: 7000, 
      theme: 'bootstrap', 
      onAdd: (toast:ToastData) => { 
       console.log('Toast ' + toast.id + ' has been added!'); 
      }, 
      onRemove: function(toast:ToastData) { 
       console.log('Toast ' + toast.id + ' has been removed!'); 
      } 
     }; 
      this.toastyService.warning(toastOptions); 
     } 

    getSuccess(SuccessTitle, SuccessMessage) { 
     var toastOptions:ToastOptions = { 
      title: SuccessTitle, 
      msg: SuccessMessage, 
      showClose: true, 
      timeout: 5000, 
      theme: 'bootstrap', 
      onAdd: (toast:ToastData) => { 
       console.log('Toast ' + toast.id + ' has been added!'); 
      }, 
      onRemove: function(toast:ToastData) { 
       console.log('Toast ' + toast.id + ' has been removed!'); 
      } 
     }; 
     this.toastyService.success(toastOptions); 
    } 

然後用戶看到正確的toast/message

成功

enter image description here

警告

enter image description here