[Angular] Create a custom validator for reactive forms in Angular
Angular for in create Custom forms reactive validator
2023-09-14 08:59:17 时间
Also check: directive for form validation
User input validation is a core part of creating proper HTML forms. Form validators not only help you to get better quality data but they also guide the user through your form. Angular comes with a series of built-in validators such as required
or maxLength
etc. But very soon you have to build your own custom validators to handle more complex scenarios. In this lesson you're going to learn how to create such custom validators for Angular's reactive forms.
Basic validator is just a function.
import { ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms'; export function nameValidator(name: string): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const isValid = control.value === '' || control.value === name; if (isValid) { return null; } else { return { nameMatch: { allowedName: name } }; } }; }
Then you can use it with the validation in Reactvie form:
import { nameValidator } from './name.validator'; this.form = this.fb.group({ firstname: ['', [Validators.required, nameValidator('someone')]] });
相关文章
- [Angular] Show a Loading Indicator for Lazy Routes in Angular
- [Angular CLI] Build application without remove dist folder for Docker Volume
- [Angular] USING ZONES IN ANGULAR FOR BETTER PERFORMANCE
- [Angular] Wrap a third party lib into service
- [Angular Directive] Implement Structural Directive Data Binding with Context in Angular
- [Angular 2] Using ng-model for two-way binding
- [AngularJS] Using the LocalForage library for offline storage with Angular
- [Angular] Show a Loading Indicator for Lazy Routes in Angular
- [Angular] Using Pipe for function memoization
- [Angular] 'providedIn' for service
- [Angular] Read Custom HTTP Headers Sent by the Server in Angular
- [Angular & Unit Testing] Testing Component with Store
- [Angular 2] ROUTING IN ANGULAR 2 REVISITED
- [AngularJS] angular-md-table for Angular material design
- [Angular 2] Using ng-for to repeat template elements
- [Angular-Scaled web] 5. ui-router $stateParams for sharing information
- [AngularJS] Using the LocalForage library for offline storage with Angular
- [Angular] In angular world and out angular world
- Angular 依赖注入错误消息:ERROR Error NullInjectorError No provider for XX
- Angular 项目中 angular.json builder 字段的可选项介绍
- Angular Route数据结构里常用字段使用方法一览