Bevezetés
Ebben a cikkben megtudhatjuk a reaktív formákban végzett validálást a szögben. Létrehozunk egy egyszerű felhasználói regisztrációs űrlapot és végrehajtunk rajta néhány beépített ellenőrzést. A beépített ellenőrzésekkel együtt néhány egyedi ellenőrzést is végrehajtunk a reaktív formában.
Ennek a bemutatónak a következő egyedi érvényesítéseit vesszük figyelembe:
- Ellenőrizze a felhasználónév elérhetőségét
- Jelszóminta érvényesítése
- Illessze be a két különböző mezőben megadott jelszót
Vessen egy pillantást az alkalmazás működésére.

Előfeltételek
- Telepítse innen a Visual Studio kódot
- Telepítse innen az Angular CLI legújabb verzióját
Forráskód
Szerezze be a forráskódot a GitHub-ból.
Hozza létre az Angular alkalmazást
Keresse meg azt a mappát, ahová létre szeretné hozni a projektfájlt. Nyissa meg a parancsablakot, és futtassa az alább látható parancsot:
ng new angular-forms-validation --routing=false --style=scss
Megadjuk az új Angular alkalmazás létrehozásának parancsát. Az útválasztási modul létrehozásának opciója hamis, és a stílusfájl kiterjesztés értéke scss
. Ez a parancs létrehozza az Angular projektet a névvel angular-forms-validation
.
Változtassa meg a könyvtárakat az új projektre, és nyissa meg a projektet a VS Code-ban az alább látható parancskészlet használatával:
cd angular-forms-validation code .
Telepítse a Bootstrap programot
Futtassa a következő parancsot a Bootstrap könyvtár telepítéséhez:
npm install bootstrap --save
Adja hozzá a következő importdefiníciót a styles.scss
fájlba:
@import "~bootstrap/dist/css/bootstrap.css";
Hozza létre az érvényesítési szolgáltatást
Új szolgáltatás létrehozásához futtassa a következő parancsot:
ng g s services\customvalidation
Ez a parancs létrehoz egy szolgáltatások nevű mappát, amelyben két fájl van - customvalidation.service.ts
és customvalidation.service.spec.ts
. Nyissa meg a customvalidation.service.ts
fájlt, és tegye bele a következő kódot:
import { Injectable } from '@angular/core'; import { ValidatorFn, AbstractControl } from '@angular/forms'; import { FormGroup } from '@angular/forms'; @Injectable({ providedIn: 'root' }) export class CustomvalidationService { patternValidator(): ValidatorFn { return (control: AbstractControl): { [key: string]: any } => { if (!control.value) { return null; } const regex = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$'); const valid = regex.test(control.value); return valid ? null : { invalidPassword: true }; }; } MatchPassword(password: string, confirmPassword: string) { return (formGroup: FormGroup) => { const passwordControl = formGroup.controls[password]; const confirmPasswordControl = formGroup.controls[confirmPassword]; if (!passwordControl || !confirmPasswordControl) { return null; } if (confirmPasswordControl.errors && !confirmPasswordControl.errors.passwordMismatch) { return null; } if (passwordControl.value !== confirmPasswordControl.value) { confirmPasswordControl.setErrors({ passwordMismatch: true }); } else { confirmPasswordControl.setErrors(null); } } } userNameValidator(userControl: AbstractControl) { return new Promise(resolve => { setTimeout(() => { if (this.validateUserName(userControl.value)) { resolve({ userNameNotAvailable: true }); } else { resolve(null); } }, 1000); }); } validateUserName(userName: string) { const UserList = ['ankit', 'admin', 'user', 'superuser']; return (UserList.indexOf(userName) > -1); } }
A módszert patternValidator
a jelszóminta érvényesítésére használjuk az űrlapunkban. A módszer paramétere olyan típusú, AbstractControl
amely a FormControl
.
A jelszó érvényesítéséhez egy reguláris kifejezést használunk. A következő négy feltételt érvényesítjük a reguláris kifejezés használatával:
- A jelszónak legalább nyolc karakter hosszúnak kell lennie.
- Legalább egy kisbetűvel rendelkezik.
- Legalább egy nagybetűvel rendelkezik.
- Legalább egy számmal rendelkezik.
Ha a jelszó nem sikerül a regex ellenőrzésen, akkor a invalidPassword
tulajdonságot igazra állítjuk .
A módszert MatchPassword
a jelszavak két mezőben történő összehasonlítására használják. Ez a módszer két karakterlánc-paramétert fogad el. Ezek a paraméterek az egyeztetendő mezők nevét jelentik. Megkapjuk a FormControl
két mező mezőt, majd megegyezünk a bennük lévő értékekkel. Ha az értékek nem egyeznek, akkor a passwordMismatch
tulajdonságot igazra állítjuk .
A módszer userNameValidator
segítségével ellenőrizhető, hogy a felhasználónév már elfoglalt-e vagy sem. Ez a módszer elfogad egy típusú paramétert AbstractControl
. Ellenőrizni fogjuk, ha a mező van jelen egy statikus tömb, UserList
. Ha a felhasználó által megadott érték már jelen van, akkor a userNameNotAvailable
tulajdonságot igazra állítjuk .
A setTimeout
függvény segítségével két másodpercenként hívjuk meg ezt az ellenőrzést. Ez biztosítja, hogy a hiba két másodperc múlva dobódjon el attól az időponttól, amikor a felhasználó abbahagyja a mezőbe történő beírást.
Hozza létre a reaktív forma komponenst
Futtassa a következő parancsot a reaktív forma összetevő létrehozásához:
ng g c reactive-form
Nyissa meg reactive-form.component.ts
és tegye be a következő kódot:
import { Component, OnInit } from '@angular/core'; import { Validators, FormGroup, FormBuilder } from '@angular/forms'; import { CustomvalidationService } from '../services/customvalidation.service'; @Component({ selector: 'app-reactive-form', templateUrl: './reactive-form.component.html', styleUrls: ['./reactive-form.component.scss'] }) export class ReactiveFormComponent implements OnInit { registerForm: FormGroup; submitted = false; constructor( private fb: FormBuilder, private customValidator: CustomvalidationService ) { } ngOnInit() { this.registerForm = this.fb.group({ name: ['', Validators.required], email: ['', [Validators.required, Validators.email]], username: ['', [Validators.required], this.customValidator.userNameValidator.bind(this.customValidator)], password: ['', Validators.compose([Validators.required, this.customValidator.patternValidator()])], confirmPassword: ['', [Validators.required]], }, { validator: this.customValidator.MatchPassword('password', 'confirmPassword'), } ); } get registerFormControl() { return this.registerForm.controls; } onSubmit() { this.submitted = true; if (this.registerForm.valid) { alert('Form Submitted succesfully!!!\n Check the values in browser console.'); console.table(this.registerForm.value); } } }
Létrehozunk egy registerForm
típusú változót FormGroup
. A ngOnInit
módszerben az FormBuilder
osztály segítségével állítjuk be az űrlap vezérlőit . Az összes mező kötelező mezőként van beállítva ehhez az űrlaphoz. Meghívjuk a userNameValidator
szolgáltatás metódusát a bind függvény segítségével.
A jelszó mezőnél a compose metódust használjuk több validátor egyesítéséhez egyetlen függvénybe. Ugyancsak meghívjuk a MatchPassword
metódust, és paraméterként átadjuk az password
és confirmPassword
űrlap vezérlők nevét .
A registerFormControl
tulajdonság visszaadja az űrlap űrlapvezérlőit. A onSubmit
módszer akkor nyomtatja ki az űrlap tartalmát a konzolra, ha az űrlap érvényes és sikeresen beküldik.
Nyissa meg reactive-form.component.html
és tegye be a következő kódot:
Angular Reactive Form
Name Name is required Email Email is required Enter a valid email address User Name User Name is required User Name is not available Password Password is required Password should have minimum 8 characters, at least 1 uppercase letter, 1 lowercase letter and 1 number Confirm Password Confirm Password is required Passwords doesnot match Register
We will create a reactive form and use the Bootstrap card for styling. The card header will contain a title whereas the card body will have the form fields. We will bind the formGroup
property of the tag to the name of our form which is
registerForm
. The onSubmit
method will be invoked on submitting the form. We will also bind the formControlName
property of each input field to the control name of our FormGroup
. We will check for errors in the form controls and then display the appropriate validation error message on the screen.
Create the nav-bar component
Run the following command to create the nav-bar component:
ng g c nav-bar
Open nav-bar.component.html
and put the following code in it:
Form Validation Demo
- Reactive Form
We are adding the navigation link to the reactive form component in the nav bar.
Update the app component
Open the app.component.html
file and put the following code in it:
Update the App module
Add the following code in the app.module.ts
file. We will import the forms module and define the routing for our application. You can refer to GitHub for the complete source code of this file.
import { RouterModule } from '@angular/router'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ ... imports: [ ... ReactiveFormsModule, RouterModule.forRoot([ { path: '', component: ReactiveFormComponent }, { path: 'reactive-form', component: ReactiveFormComponent } ]), ], })
Execution demo
We will use the following command to start the web server:
ng serve -o
This command will launch the application in your default browser at //localhost:4200/
. You can perform all the form validations which we have discussed here.
This application is also hosted at //ng-forms-validation.herokuapp.com/. Navigate to the link and play around with it for a better understanding.
Summary
We have created a sample user registration form using the reactive form approach in Angular. We have implemented the inbuilt validations as well as custom validations to the form. The Bootstrap library is used to style the form.
Get the source code from GitHub and play around with it for a better understanding.
See Also
- Localization In Angular Using i18n Tools
- Template-Driven Form Validation In Angular
- Understanding Angular Animation
- Policy-Based Authorization In Angular Using JWT
- Facebook Authentication And Authorization In Server-Side Blazor App
You can find other posts like Reactive Form Validation in Angular on Ankit Sharma's Blog.