欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Angular实现表单验证功能

程序员文章站 2022-06-18 08:30:26
angular表单验证分为两种验证:1.内置验证(required,minlength等);2.自定义验证(正则表达式)。 接下来我们用一个注册账号的demo来看一下这两...

angular表单验证分为两种验证:1.内置验证(required,minlength等);2.自定义验证(正则表达式)。

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

项目界面

Angular实现表单验证功能

一、内置验证

其中账户名有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

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

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.项目效果

Angular实现表单验证功能

二、自定义验证

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

1.项目目录

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

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

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

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

----------emailauthentication.ts

2.项目代码

app.module.ts

注册自定义验证器emailvalidatordirective

import { browsermodule } from '@angular/platform-browser';
import { ngmodule } from '@angular/core';
import { formsmodule,reactiveformsmodule }  from '@angular/forms';
import { emailvalidatordirective } from './emailauthentication';

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

@ngmodule({
 declarations: [
  appcomponent,
  emailvalidatordirective
 ],
 imports: [
  browsermodule,
  formsmodule,
  reactiveformsmodule
 ],
 providers: [],
 bootstrap: [appcomponent]
})
export class appmodule { }

emailauthentication.ts

import { directive, input, onchanges, simplechanges } from '@angular/core';
import { abstractcontrol, ng_validators, validator, validatorfn, validators } from '@angular/forms';

/** a hero's name can'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 ? { 'forbiddenname': { value: control.value } } : null;
  };
}

@directive({
  selector: '[appforbiddenname]',
  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, 'i'))(control)
      : null;
  }
}

app.component.ts

import { component,oninit } from '@angular/core';
import { formgroup, formcontrol, validators } from '@angular/forms';
import { emailvalidator } from './emailauthentication'; //导入emailvalidator自定义验证器

@component({
 selector: 'app-root',
 templateurl: './app.component.html',
 styleurls: ['./app.component.css']
})
export class appcomponent {
 title = 'app';
 //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({
      'name': new formcontrol(this.data.name, [
       validators.required,
       validators.minlength(4)
      ]),
      'email': new formcontrol(this.data.email, [
        validators.required,
        emailvalidator(this.emailexp) //自定义验证器
        ]),
      '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'); }
}

app.component.html

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

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

3.项目效果

Angular实现表单验证功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。