Rumah >hujung hadapan web >tutorial js >详解Angular实现表单验证功能

详解Angular实现表单验证功能

小云云
小云云asal
2017-12-21 13:10:072083semak imbas

Angular表单验证分为两种验证:1.内置验证(required,minlength等);2.自定义验证(正则表达式)。本文主要为大家详细介绍了Angular实现表单验证功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能帮助到大家。

接下来我们用一个注册账号的demo来看一下这两种验证是如何实现的。

项目界面

一、内置验证

其中账户名有required验证和最短长度验证,其他两个只有required验证

1.项目目录

----------app.component.ts

----------app.component.html

----------app.component.css

----------app.module.ts

2.项目代码

app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule,ReactiveFormsModule }  from '@angular/forms';//表单验证必须导入这两个模块

import { AppComponent } from './app.component';

@NgModule({
 declarations: [
  AppComponent
 ],
 imports: [
  BrowserModule,
  FormsModule,  //注册模块
  ReactiveFormsModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts


import { Component,OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'app';
 Form:FormGroup;
 data={
   name:"",
   email:"",
   tel:""
 }
 ngOnInit(): void {
   this.Form = new FormGroup({
      'name': new FormControl(this.data.name, [
       Validators.required,
       Validators.minLength(4)
      ]),
      'email': new FormControl(this.data.email, Validators.required),
      'tel': new FormControl(this.data.tel, Validators.required)
     });
  }

  get name() { return this.Form.get('name'); }
  get email() { return this.Form.get('email'); }
  get tel() { return this.Form.get('tel'); }
}

简单来说,在使用验证表单的时候,大致分为四步:

(1)导入相关模块FormGroup, FormControl, Validators;

(2)声明表单验证变量From:FromGroup;

(3)定义验证规则;

(4)通过它所属的控件组(FormGroup)的get方法来访问表单控件

app.component.html


<p class="wrapper">
  <p class="row">
    <p class="title-wrapper">注册账号</p>
  </p>
  <p class="row">
    <p class="contain-wrapper" [formGroup]="Form">
      <label for="name">账户名:</label>
      <input type="text" id="name" formControlName="name"><br/>
      <p *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
        <p *ngIf="name.errors.required">
          请输入长度账户名!
        </p>
        <p *ngIf="name.errors.minlength">
          账户名长度不小于4!
        </p>
      </p>
      <label for="email">邮箱:</label>
      <input type="text" id="email" formControlName="email"><br/>
      <p *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger">
        <p *ngIf="email.errors.required">
          请输入邮箱!
        </p>
      </p>
      <label for="tel">电话:</label>
      <input type="text" id="tel" formControlName="tel">
      <p *ngIf="tel.invalid && (tel.dirty || tel.touched)" class="alert alert-danger">
        <p *ngIf="tel.errors.required">
          请输入电话!
        </p>
      </p>
    </p>
  </p>
  <p class="row">
    <button class="btn btn-primary confirm">确认</button>
  </p>
</p>

app.component.css


*{
  font-size: 18px;
}
.wrapper{
  margin: 0 auto;
  margin-top:10%;
  width:30%;
  height: 20%;
  border:1px solid black;
  border-radius: 10px;
}

.title-wrapper{
  margin: 0 auto;
  padding-top: 20px; 
  padding-bottom: 20px;
  width:370px;
  text-align: center;
  font-size: 20px;
  font-weight: 800;
}
label{
  display: inline-block;
  width:72px;
}
.contain-wrapper{
  width: 300px;
  margin:0 auto;
}
.confirm{
  margin-top:20px;
  width:100%;

}

3.项目效果

二、自定义验证

自定义表单验证,需要创建自定义验证器,我们接下来更改邮箱的验证,将其改为有格式的验证,而不是单纯的存在验证,首先我们来看一下项目目录的更改

1.项目目录

----------app.component.ts

----------app.component.html

----------app.component.css

----------app.module.ts

----------emailAuthentication.ts

2.项目代码

app.module.ts

注册自定义验证器EmailValidatorDirective


import { BrowserModule } from &#39;@angular/platform-browser&#39;;
import { NgModule } from &#39;@angular/core&#39;;
import { FormsModule,ReactiveFormsModule }  from &#39;@angular/forms&#39;;
import { EmailValidatorDirective } from &#39;./emailAuthentication&#39;;

import { AppComponent } from &#39;./app.component&#39;;

@NgModule({
 declarations: [
  AppComponent,
  EmailValidatorDirective
 ],
 imports: [
  BrowserModule,
  FormsModule,
  ReactiveFormsModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

emailAuthentication.ts


import { Directive, Input, OnChanges, SimpleChanges } from &#39;@angular/core&#39;;
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from &#39;@angular/forms&#39;;

/** A hero&#39;s name can&#39;t match the given regular expression */
export function emailValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    const forbidden = !nameRe.test(control.value);
    return forbidden ? { &#39;forbiddenName&#39;: { value: control.value } } : null;
  };
}

@Directive({
  selector: &#39;[appForbiddenName]&#39;,
  providers: [{ provide: NG_VALIDATORS, useExisting: EmailValidatorDirective, multi: true }]
})
export class EmailValidatorDirective implements Validator {
  @Input() forbiddenName: string;

  validate(control: AbstractControl): { [key: string]: any } {
    return this.forbiddenName ? emailValidator(new RegExp(this.forbiddenName, &#39;i&#39;))(control)
      : null;
  }
}

app.component.ts


import { Component,OnInit } from &#39;@angular/core&#39;;
import { FormGroup, FormControl, Validators } from &#39;@angular/forms&#39;;
import { emailValidator } from &#39;./emailAuthentication&#39;; //导入emailValidator自定义验证器

@Component({
 selector: &#39;app-root&#39;,
 templateUrl: &#39;./app.component.html&#39;,
 styleUrls: [&#39;./app.component.css&#39;]
})
export class AppComponent {
 title = &#39;app&#39;;
 //email的正则表达式
 emailExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/ ;
 Form:FormGroup;
 data={
   name:"",
   email:"",
   tel:""
 }
 ngOnInit(): void {
   this.Form = new FormGroup({
      &#39;name&#39;: new FormControl(this.data.name, [
       Validators.required,
       Validators.minLength(4)
      ]),
      &#39;email&#39;: new FormControl(this.data.email, [
        Validators.required,
        emailValidator(this.emailExp) //自定义验证器
        ]),
      &#39;tel&#39;: new FormControl(this.data.tel, Validators.required)
     });
  }

  get name() { return this.Form.get(&#39;name&#39;); }
  get email() { return this.Form.get(&#39;email&#39;); }
  get tel() { return this.Form.get(&#39;tel&#39;); }
}

app.component.html


<p class="wrapper">
  <p class="row">
    <p class="title-wrapper">注册账号</p>
  </p>
  <p class="row">
    <p class="contain-wrapper" [formGroup]="Form">
      <label for="name">账户名:</label>
      <input type="text" id="name" formControlName="name"><br/>
      <p *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
        <p *ngIf="name.errors.required">
          请输入账户名!
        </p>
        <p *ngIf="name.errors.minlength">
          账户名长度不小于4!
        </p>
      </p>
      <label for="email">邮箱:</label>
      <input type="text" id="email" formControlName="email" required><br/>
      <p *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger">
        <p *ngIf="email.errors.forbiddenName">
         请输入正确格式的邮箱!
        </p>
      </p>
      <label for="tel">电话:</label>
      <input type="text" id="tel" formControlName="tel">
      <p *ngIf="tel.invalid && (tel.dirty || tel.touched)" class="alert alert-danger">
        <p *ngIf="tel.errors.required">
          请输入电话!
        </p>
      </p>
    </p>
  </p>
  <p class="row">
    <button class="btn btn-primary confirm" [disabled]="Form.invalid" >确认</button>
  </p>
</p>

在最后确认的时候,我们设置一下按钮的disabled属性,在表单验证不通过的时候,确认按钮是点击不了的,显示不可点击状态。[disabled]="Form.invalid"。

3.项目效果

相关推荐:

jquery表单验证插件

jQuery表单验证的实例代码

JavaScript中实现表单验证

Atas ialah kandungan terperinci 详解Angular实现表单验证功能. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn