当前位置:Gxlcms > JavaScript > angular2之ng2-validation学习

angular2之ng2-validation学习

时间:2021-07-01 10:21:17 帮助过:15人阅读

最近在使用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 { }
View Code

表单验证的使用方式有两种。可以灵活选择。两者混合使用我没研究。其实使用一种就足够了。

模板驱动template driven

GitHub上例子

<input type="text" [(ngModel)]="model.field" name="field" #field="ngModel" [rangeLength]="[5, 9]"/>
<p *ngIf="field.errors?.rangeLength">error message</p>
模型驱动(model driven)
GitHub上例子
<
<p *ngIf="demoForm.from.controls.field.errors?.rangeLength">error message</p>
FormGroup需要在from的dom上添加formGroup驱动,否则验证不生效。
  <form [formGroup]="formGroup" (ngSubmit)="onSubmit()" #validationForm2="ngForm" >
 下面是我的demo代码片段:
模板驱动app-ttemplate-driven.component.html
<div class="container">
  <form (ngSubmit)="onSubmit()" #validationForm="ngForm">
    <div class="form-group">
      <label for="appField">长度要求</label>
      <input type="text" required class="form-control" name="appField" [(ngModel)]="model.appField" #rangeLength="ngModel" [rangeLength]="[5, 9]">
      <p [hidden]="rangeLength.valid||rangeLength.pristine">长度在5到9之间</p>
    </div>
    <div class="form-group">
      <label for="appField2">长度要求2</label>
      <input type="text"  class="form-control" name="appField2" [(ngModel)]="model.appField2" #rangeLength2="ngModel" [rangeLength]="[0,5]">
      <p [hidden]="rangeLength2.valid||rangeLength2.pristine">长度要求</p>
    </div>
    <div class="form-group">
      <label for="appMin">最小值</label>
      <input type="number"  class="form-control" name="appMin" [(ngModel)]="model.appMin"  #appMin="ngModel" [min]="10" />
     <p [hidden]="appMin.valid||appMin.pristine">取值大于等于10</p>
    </div>
   <div class="form-group">
     <label for="appGt">大于</label>
     <input type="number" class="form-control" name="appGt" [(ngModel)]="model.appGt" #appGt="ngModel" [gt]="10" />
     <p [hidden]="appGt.valid||appGt.pristine">取值大于10</p>
   </div>
   <div class="form-group">
     <label for="appGte">大于等于</label>
     <input type="number" class="form-control" name="appGte" [(ngModel)]="model.appGte" #appGte="ngModel" [gte]="10" />
     <p [hidden]="appGte.valid||appGte.pristine">取值大于等于10</p>
   </div>
   <div class="form-group">
     <label for="appMax">最大值</label>
     <input type="number" class="form-control" name="appMax" [(ngModel)]="model.appMax" #appMax="ngModel" [max]="10" />
     <p [hidden]="appMax.valid||appMax.pristine">最小值10</p>
   </div>
    <div class="form-group">
     <label for="appLt">小于</label>
     <input type="number" class="form-control" name="appLt" [(ngModel)]="model.appLt" #appLt="ngModel" [lt]="10" />
     <p [hidden]="appLt.valid||appLt.pristine">值小于10</p>
   </div>
   <div class="form-group">
     <label for="appLte">小于等于</label>
     <input type="number" class="form-control" name="appLte" [(ngModel)]="model.appLte" #appLte="ngModel" [lte]="10" />
     <p [hidden]="appLte.valid||appLte.pristine">值小于等于10</p>
   </div>
   <div class="form-group">
     <label for="appRange">取值范围</label>
     <input type="number" class="form-control" name="appRange" [(ngModel)]="model.appRange" #appRange="ngModel" [range]="[10, 20]" />
     <p [hidden]="appRange.valid||appRange.pristine">取值大于等于10到小于等于20</p>
   </div>
   <div class="form-group">
     <label for="appDigits">数字</label>
     <input type="text" class="form-control" name="appDigits" [(ngModel)]="model.appDigits" #appDigits="ngModel" digits />
     <p [hidden]="appDigits.valid||appDigits.pristine">必须是uint</p>
   </div>
   <div class="form-group">
     <label for="appNumber">数字</label>
     <input type="text" class="form-control" name="appNumber" [(ngModel)]="model.appNumber" #appNumber="ngModel" number />
     <p [hidden]="appNumber.valid||appNumber.pristine">任何数字</p>
   </div>
   <div class="form-group">
     <label for="appUrl">链接</label>
     <input type="text" class="form-control" name="appUrl" [(ngModel)]="model.appUrl" #appUrl="ngModel" url />
     <p [hidden]="appUrl.valid||appUrl.pristine">合法的url</p>
   </div>
    <div class="form-group">
     <label for="appEmail">邮箱</label>
     <input type="text" class="form-control" name="appEmail" [(ngModel)]="model.appEmail" #appEmail="ngModel" email />
     <p [hidden]="appEmail.valid||appEmail.pristine">合法的邮箱地址</p>
   </div>
   <div class="form-group">
     <label for="appDate">日期</label>
     <input type="text" class="form-control" name="appDate" [(ngModel)]="model.appDate" #appDate="ngModel" date />
     <p [hidden]="appDate.valid||appDate.pristine">合法的日期</p>
   </div>
   <div class="form-group">
     <label for="appUuid">uuid</label>
     <input type="text" class="form-control" name="appUuid" [(ngModel)]="model.appUuid" #appUuid="ngModel" uuid="'all'" />
     <p [hidden]="appUuid.valid||appUuid.pristine">不是合法的uuid</p>
   </div>
   <div class="form-group">
     <label for="appPhone">电话</label>
     <input type="text" class="form-control" name="appPhone" [(ngModel)]="model.appPhone" #appPhone="ngModel" phone="CN" />
     <p [hidden]="appPhone.valid||appPhone.pristine">不是合法的电话号码</p>
   </div>
   <div class="form-group">
     <label >两次相同</label>
     <input class="form-control"  type="password" ngModel name="appPassword" #appPassword="ngModel" required/>
     <p [hidden]="appPassword.valid||appPassword.pristine">必填项</p>
     <input class="form-control"  type="password" ngModel name="appCertainPassword" #appCertainPassword="ngModel" [equalTo]="appPassword"/>
     <p [hidden]="appCertainPassword.valid||appCertainPassword.pristine">两次输入不一致</p>
   </div>
   <div class="form-group">
     <label for="appEqual">相同</label>
     <input type="text" class="form-control" name="appEqual" [(ngModel)]="model.appEqual" #appEqual="ngModel" [equal]="'哈哈'" />
     <p [hidden]="appEqual.valid||appEqual.pristine">与值不相符</p>
   </div>
    <div class="form-group">
     <label for="appComplex">复合条件</label>
     <input type="number" class="form-control" name="appComplex" [(ngModel)]="model.appComplex" #appComplex="ngModel" [gte]="5" [max]="10"  />
     <p [hidden]="appComplex.valid||appComplex.pristine">大于等于5,最大是10</p>
   </div>
    <button type="submit" [disabled]="!validationForm.form.valid" class="btn btn-default">Submit</button>
  </form>
</div>
View Code

 

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(){}
}
View Code

app-model-driven.component.html

<div class="container">
  <form [formGroup]="formGroup" (ngSubmit)="onSubmit()" #validationForm2="ngForm" >
    <div class="form-group" >
      <input class="form-control" name="field"  type="text"  formControlName="field"/>
      <p *ngIf="validationForm2.form.controls.field.errors?.rangeLength">长度在5到9之间</p>
      <p>{{validationForm2.form.controls.field.errors?.rangeLength}}</p>
    </div>
   <div class="form-group" >
      <input class="form-control" name="appGt" type="number"  formControlName="appGt"/>
      <p *ngIf="validationForm2.form.controls.appGt.errors?.gt">大于10</p>
    </div>
    <div class="form-group" >
      <input class="form-control" name="password" type="password" [(ngModel)]="password" formControlName="password"/>
      <p *ngIf="validationForm2.form.controls.password.errors?.required">必填</p>
      <p>{{test.pristine}}</p>
      <input class="form-control" type="password" formControlName="certainPassword"/>
      <p *ngIf="validationForm2.form.controls.certainPassword.errors?.equalTo">两次相同</p>
    </div>
    <div class="form-group" >
      <label for="appMin">组合形式</label>
      <input type="number"  class="form-control" name="appMin" formControlName="maxField" />
     <p [hidden]="!validationForm2.form.controls.maxField.errors?.max &&!validationForm2.form.controls.maxField.errors?.gt">取值大于等于10且小于20</p>
    </div>
    <button type="submit" [disabled]="!validationForm2.form.valid" class="btn btn-default">Submit</button>
  </form>
</div>
View Code

 
 

以上就是angular2之ng2-validation学习的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行