最近在使用ng2做前端。发现表单验证这块除了官网上给的示例,验证required。其他的都要自己写逻辑来实现。开发起来不是很方便。所以在网上找了下ng2表单验证的资源,觉得ng2-validation不错。所以做的例子。以便以后使用,也怕时间久了忘脑后去。
示例代码链接
首先从npm包管理服务器上下载安装。
npm install ng2-validation --save 命令参数--save:使npm包信息保存在package.json文件的dependencies配置集合内。该集合是ng2正式运行的依赖集合。
使用方法
在模块文件内添加引用,一般为AppModule。
app.module.ts文件


import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule,ReactiveFormsModule } from '@angular/forms';import { CustomFormsModule } from 'ng2-validation';import { AppComponent } from './app.component';import { AppTtemplateDrivenComponent } from './app-ttemplate-driven/app-ttemplate-driven.component';import { AppModelDrivenComponent } from './app-model-driven/app-model-driven.component';import { AppRoutingModule } from "app/app-routes.module";import { ValidationConfigModel } from "app/Models/validation";
@NgModule({
declarations: [
AppComponent,
AppTtemplateDrivenComponent,
AppModelDrivenComponent
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
CustomFormsModule,
ReactiveFormsModule
],
providers: [ValidationConfigModel],
bootstrap: [AppComponent]
})
export class AppModule { }
表单验证的使用方式有两种。可以灵活选择。两者混合使用我没研究。其实使用一种就足够了。
模板驱动(template driven)
GitHub上例子
error message
<
<p *ngIf="demoForm.from.controls.field.errors?.rangeLength">error messagep>
FormGroup需要在from的dom上添加formGroup驱动,否则验证不生效。
下面是我的demo代码片段:
模板驱动app-ttemplate-driven.component.html


ts文件不需要做什么,所以就不贴了。
模型驱动
app-model-driven.component.ts


import { Component, OnInit } from '@angular/core';import { FormGroup, FormControl, Validators } from "@angular/forms";import { CustomValidators } from 'ng2-validation';
@Component({
selector: 'app-app-model-driven',
templateUrl: './app-model-driven.component.html',
styleUrls: ['./app-model-driven.component.css']
})
export class AppModelDrivenComponent implements OnInit {public formGroup: FormGroup;
password:string="";
constructor() {
let password = new FormControl('', [Validators.required]);
let certainPassword = new FormControl('', CustomValidators.equalTo(password));this.formGroup = new FormGroup({
field: new FormControl('', CustomValidators.rangeLength([5, 9])),
appGt:new FormControl('', CustomValidators.gt(10)),
password:password,
certainPassword:certainPassword,
maxField:new FormControl('',[CustomValidators.gt(10),CustomValidators.max(20)])
});
}
ngOnInit() {
}
onSubmit(){}
}app-model-driven.component.html












