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 在服务里声明返回类别方法
getAllCategories():string[]{ return ["电子产品","硬件设备","图书"]; }