


How to operate Angular to implement custom validation functions of template-driven forms
This time I will show you how to operate Angular to implement the custom verification function of template-driven forms, and how to operate Angular to implement the custom verification function of template-driven forms. What are the precautions?, the following is the actual combat Let’s take a look at the case.
HTML5’s native form validation attributes (required, length limit, value interval, regular expression, etc.) can meet ordinary validation needs, but they must be used in some scenarios Custom verification, such as password confirmation during registration, time/value selection with comparison relationship, request to the server for value verification, etc... Here we take password confirmation as an example.
Command development
The verification status of the form is fed back through the errors attribute of formControl, so the basic idea is to add validation Validation rules, and then add the validation results to the errors attribute of the formControl instance. Then the problem comes, the control of the template-driven form is completed in the HTML template, and the formControl instance cannot be directly accessed. At this time, you need to use instructions to package the inspection rules. Angular provides Validator supplier NG_VALIDATORS for handling form custom validation. Create the directive first.
import { Directive} from '@angular/core'; import { NG_VALIDATORS, Validator, AbstractControl} from '@angular/forms'; @Directive({ selector: '[appConfirmpsw]', providers: [{ provide : NG_VALIDATORS, useExisting : ConfirmpswDirective, multi: true }] }) export class ConfirmpswDirective implements Validator { constructor() { } validate(control: AbstractControl): {[key: string]: any} { //检验规则 } }
1. Specify the provider for the instruction NG_VALIDATORS, and the alias class ConfirmpswDirective, and multi is true (you can use the same token to register different providers). Because it is a directive registered in the NG_VALIDATORS provider, it can be recognized by Angular's verification process. It should be noted that it must be registered with useExisting so that a new instance will not be created.
2. Use the Validator interface to constrain custom instructions. This is the validator class provided by Angular. There is a validate attribute, which will pass in the formControl of the form and return a ValidationErrors object.
Now that the command structure is completed, the verification part begins. First, you need to pass in the entered password, so add @input, and then specify the verification rules to determine whether the value of the bound form is the same as the entered value
@Input('appConfirmpsw') confirmpsw: string;
In order to avoid using instructions, you also need to Additionally pass in the confirmpsw attribute ( <input type="password" appConfirmpsw [confirmpsw]="'xxx'" >
), so we use the command name appConfirmpsw as an alias of confirmpsw, so that the passed values will be compared Convenient, simplified to <input type="password" [appConfirmpsw] = "'xxx'">
.
Here is a specially written test function to compare values and return results. Remember to call
export function comfirmPswValidator(_confirmpsw: string): ValidatorFn { //传入已输入的密码值 , 返回一个ValidatorFn return (control: AbstractControl): {[key: string]: any} => { //传入绑定表单的formControl if ( !control.value ) { //如果绑定未输入值,则返回 required错误 return { 'required' : true }; } //如果两次输入的值不相同,则返回confirmpsw的错误 return control.value !== _confirmpsw ? {'confirmpsw' : {value: true}} : null; }; }
in the validate of the command. The complete command is as follows:
import { Directive, Input } from '@angular/core'; import { NG_VALIDATORS, Validator, AbstractControl, ValidatorFn} from '@angular/forms'; @Directive({ selector: '[appConfirmpsw]', providers: [{ provide : NG_VALIDATORS, useExisting : ConfirmpswDirective, multi: true }] }) export class ConfirmpswDirective implements Validator { @Input('appConfirmpsw') confirmpsw: string; constructor() { } validate(control: AbstractControl): {[key: string]: any} { console.log(this.confirmpsw); return this.confirmpsw ? comfirmPswValidator(this.confirmpsw)(control) : null; } } export function comfirmPswValidator(_confirmpsw: string): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { if ( !control.value ) { return { 'required' : true }; } return control.value !== _confirmpsw ? {'confirmpsw' : {value: true}} : null; }; }
Use
to test the effect of the command Bar
<p class="input-group"> <label class="group-label" for="psw-new"> 新密码 :</label> <input class="group-input" [(ngModel)]="inputpsw.new" #new="ngModel" type="password" name="psw" id="psw-new" required> </p> <p class="input-group input-error" *ngIf="new.touched&&new.invalid"> <p class="group-error-content" *ngIf="new.errors?.required">确认密码为必填项!</p> </p> <p class="input-group"> <label class="group-label" for="psw-confirm">确认密码 :</label> <input class="group-input" [(ngModel)]="inputpsw.confirm" #confirm="ngModel" type="password" name="confirm" id="psw-confirm" [appConfirmpsw] = "new.value" required> </p> <p class="input-group input-error" *ngIf="confirm.touched&&confirm.invalid"> <p class="group-error-content" *ngIf="confirm.errors?.required">新密码为必填项!</p> <p class="group-error-content" *ngIf="confirm.errors?.confirmpsw">密码输入不一致!</p> </p>
Pass in the value of the new form, and control the prompt feedback through the errors.confirmpsw
attribute. The password input is inconsistent and can be correctly verified to
. The prompt when confirming that the password is empty is also correct
believe it After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to deal with Mac installation thrift error due to bison
How to use Taobao mirror cnpm to install Vue.js
The above is the detailed content of How to operate Angular to implement custom validation functions of template-driven forms. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.
