首頁  >  文章  >  web前端  >  詳解Angular實作表單驗證功能

詳解Angular實作表單驗證功能

小云云
小云云原創
2017-12-21 13:10:072034瀏覽

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中實作表單驗證

#

以上是詳解Angular實作表單驗證功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn