angular4 form表單驗證

<!-- novalidate 清除瀏覽器默認的校驗行爲 -->
<form [formGroup]="formModel" (ngSubmit)="onSearch()" novalidate>
    <div class="form-group" [class.has-error]="formModel.hasError('minlength','title')">
        <label for="productTitle">商品名稱:</label>
        <input formControlName="title" type="text" id="productTitle" placeholder="商品名稱" class="form-control">
        <span class="help-block" [class.hidden]="!formModel.hasError('minlength','title')"> 請至少輸入三個字 </span>
    </div>
    <div class="form-group" [class.has-error]="formModel.hasError('positiveNumber','price')">
        <label for="productPrice">商品價格:</label>
        <input formControlName="price" type="number" id="productPrice" placeholder="商品價格" class="form-control">
        <span class="help-block" [class.hidden]="!formModel.hasError('positiveNumber','price')"> 請輸入正數 </span>
    </div>
    <div class="form-group">
        <label for="productCategory">商品類別:</label>
        <select formControlName="category" id="productCategory" class="form-control">
            <option value="-1">所有分類</option>
            <option *ngFor="let category of categories" [value]="category">{{category}}</option>
        </select>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">搜索</button>
    </div>
</form>
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators,FormControl } from '@angular/forms'; import { ProductService } from '../share/product.service'; @Component({ selector: 'app-search', templateUrl: './search.component.html', styleUrls: ['./search.component.scss'] }) export class SearchComponent implements OnInit { formModel:FormGroup; categories: string[]; constructor(private productService:ProductService) { let fb = new FormBuilder(); this.formModel = fb.group({ title:['',Validators.minLength(3)], //最少很多於3個字符
        price:[null,this.positiveNumberValidator], //不能爲負數
        category:['-1'] //默認值爲-1 --所有分類
 }) } ngOnInit() { this.categories = this.productService.getAllCategories(); } positiveNumberValidator(control: FormControl):any{ if(!control.value){//若是輸入爲空則返回空,至關於去空格
          return null; } let price = parseInt(control.value); if(price>0){ // 若是大於0不顯示錯誤信息
          return null; }else{  // 不大於0則顯示錯誤信息
          return {positiveNumber:true}; } } //若是驗證經過的話就把表單對應的值打印到控制檯
 onSearch(){ if(this.formModel.valid){ console.log(this.formModel.value); } } }

productService.ts 在服務裏聲明返回類別方法css

getAllCategories():string[]{ return ["電子產品","硬件設備","圖書"]; }
相關文章
相關標籤/搜索