angular2 表单验证方式有两种:
1.模块驱动
install
npm install ng2-validation --save
import FormsModule
and CustomFormsModule
in app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { CustomFormsModule } from 'ng2-validation' import { AppComponent } from './app.component'; @NgModule({ imports: [BrowserModule, FormsModule, CustomFormsModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { }
html
<input type="text" [(ngModel)]="model.field" name="field" #field="ngModel" [rangeLength]="[5, 9]"/> <p *ngIf="field.errors?.rangeLength">error message</p>注意 :具体可参照https://github.com/yuyang041060120/ng2-validation上所说的,比较简单,直接引入按要求使用就行。
2.模型驱动
install
npm install ng2-validation --save
import ReactiveFormsModule
in app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { }
import CustomValidators
in app.component.ts
import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { CustomValidators } from 'ng2-validation'; @Component({ selector: 'app', template: require('./app.html') }) export class AppComponent {
formGroup:
FormGroup;
constructor(){
this.
formGroup =
new
FormGroup({
field:
new
FormControl(
'',
CustomValidators.
rangeLength([
5,
9]))
});
}
}
html
<form [formGroup]="formGroup" #myForm="ngForm">
<div class="form-conctrol">
<input type="text" [(ngModel)]="test" name="field" formControlName="field" required/>
<p *ngIf="formGroup.controls.field.errors?.rangeLength">error message</p>
</div>
</form>
注意:需要注意的地方是,form必须添加驱动[formGroup]="formGroup",才能触发生效。
其他简单的,完全可以参照https://github.com/yuyang041060120/ng2-validation,这里主要是为了解释下模型驱动的写法,因为例子,写的有问题。