angular2表单验证

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,这里主要是为了解释下模型驱动的写法,因为例子,写的有问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值