Angular implements Form Verification and angular form verification

Source: Internet
Author: User
Tags export class

Angular implements Form Verification and angular form verification

Angular form verification can be divided into two types: 1. built-in verification (required, minlength, etc.); 2. Custom verification (regular expression ).

Next we will use the demo of a registered account to see how the two verification methods are implemented.

Project Interface

1. built-in verification

The account names are verified by required and shortest length. The other two are verified by required.

1. project directory

---------- App. component. ts

----------App.component.html

----------App.component.css

---------- App. module. ts

2. project code

App. module. ts

Import {BrowserModule} from '@ angular/platform-browser'; import {NgModule} from' @ angular/core'; import {FormsModule, ReactiveFormsModule} from '@ angular/forms '; // form verification must import these two modules 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'); }}

To put it simply, the verification form is divided into four steps:

(1) import the relevant modules FormGroup, FormControl, Validators;

(2) Declare the Form Verification variable From: FromGroup;

(3) define verification rules;

(4) access the form control through the get method of its control group (FormGroup)

App.component.html

<Div class = "wrapper"> <div class = "row"> <p class = "title-wrapper"> register an account </p> </div> <div class = "row"> <div class = "contain-wrapper" [formGroup] = "Form"> <label for = "name"> Account name: </label> <input type = "text" id = "name" formControlName = "name"> <br/> <div * ngIf = "name. invalid & (name. dirty | name. touched) "class =" alert-danger "> <div * ngIf =" name. errors. required "> enter the length of your account name! </Div> <div * ngIf = "name. errors. minlength"> the length of the account name is no less than 4! </Div> <label for = "email"> email: </label> <input type = "text" id = "email" formControlName = "email"> <br/> <div * ngIf = "email. invalid & (email. dirty | email. touched) "class =" alert-danger "> <div * ngIf =" email. errors. required "> enter your email address! </Div> <label for = "tel"> tel: </label> <input type = "text" id = "tel" formControlName = "tel"> <div * ngIf = "tel. invalid & (tel. dirty | tel. touched) "class =" alert-danger "> <div * ngIf =" tel. errors. required "> enter your phone number! </Div> <div class = "row"> <button class = "btn-primary confirm"> OK </button> </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. Project Effect

Ii. Custom Verification

For user-defined form verification, you need to create a user-defined validators. Next, we will change the mailbox verification to a format verification, instead of simply verifying the existence, first, let's take a look at the changes to the project directory.

1. project directory

---------- App. component. ts

----------App.component.html

----------App.component.css

---------- App. module. ts

---------- EmailAuthentication. ts

2. project code

App. module. ts

Register the custom validators 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 '; // import the emailValidator User-Defined validators @ Component ({selector: 'app-root', templateUrl :'. /app.component.html ', styleUrls :['. /app.component.css ']}) export class AppComponent {title = 'app'; // The Regular Expression of 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) // User-Defined validators]), '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"> register an account </p> </div> <div class = "row"> <div class = "contain-wrapper" [formGroup] = "Form"> <label for = "name"> Account name: </label> <input type = "text" id = "name" formControlName = "name"> <br/> <div * ngIf = "name. invalid & (name. dirty | name. touched) "class =" alert-danger "> <div * ngIf =" name. errors. required "> enter the account name! </Div> <div * ngIf = "name. errors. minlength"> the length of the account name is no less than 4! </Div> <label for = "email"> email: </label> <input type = "text" id = "email" formControlName = "email" required> <br/> <div * ngIf = "email. invalid & (email. dirty | email. touched) "class =" alert-danger "> <div * ngIf =" email. errors. forbiddenName "> enter an email address in the correct format! </Div> <label for = "tel"> tel: </label> <input type = "text" id = "tel" formControlName = "tel"> <div * ngIf = "tel. invalid & (tel. dirty | tel. touched) "class =" alert-danger "> <div * ngIf =" tel. errors. required "> enter your phone number! </Div> <div class = "row"> <button class = "btn-primary confirm" [disabled] =" form. invalid "> OK </button> </div>

During the final confirmation, we set the disabled attribute of the button. When the form verification fails, the confirmation button cannot be clicked, And the unclickable status is displayed. [Disabled] = "Form. invalid ".

3. Project Effect

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.