Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Angular forms to validate gracefully

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article focuses on "how to use Angular form validation elegantly". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Angular form validation gracefully.

When it comes to forms, I think a strong form should contain the following three parts of functionality

1. Collecting the form data entered by the user, it is very convenient to realize two-way binding through ngModel syntax sugar in Angular.

two。 Various validators are used to verify whether the data entered by form elements is legal. Angular has built-in commonly used validators (required, pattern, email,min,max,minlength,maxlength).

3. Give feedback to the user after verification, such as verification without giving the wrong message.

I think Angular's form is undoubtedly the most powerful of the three frameworks, without one, and it is the official native support and maintenance. When it comes to Angular's form, you must say Angular.js 's form. In fact, Angular's form basically inherits all the functions of Angular.js form, and at the same time, it is more powerful than Angular.js and API is more friendly.

So what are the improvements in Angular's form compared with Angular.js?

1. Custom ngModel

In Angular.js, ng-model can only be used for built-in HTML form elements such as input,select. If it is a custom select box (div), you may not be able to use your own validators such as required.

But it can be handled in a nasty way, such as adding a hidden native HTML form element, where the ng-model bound to this element is the same as the model of the custom select box, and then whether the hidden element is verified by controlling the validation style of the custom Select

Then in Angular, you can easily let any custom component use ngModel and built-in validator, as long as your custom component implements ControlValueAccessor interface and adds NG_VALUE_ACCESSOR 's provider to the component's providers. Specific how to implement a custom support ngModel component to search by itself, the official document does not seem to find the relevant introduction, with a stackoverflow question attached.

two。 Automatic recognition of form elements within structured instructions

If there is a dynamic instruction such as ng-if in Angular.js, the internal form elements will not be automatically appended to Form, but must be manually appended to ngForm by extending a custom directive-- dynamicFormControl-- but there is no need for users to deal with them in Angular. As long as the elements are rendered, they will be automatically appended to ngForm Controls.

3. Responsive form

In addition to template-driven forms, Angular-responsive forms are also added in Angular, giving users one more choice, and responsive forms have an advantage in some complex scenarios.

4. Better support for dynamic forms

In Angular, both template-driven forms and responsive forms have good support for dynamic form creation, and you can easily create dynamic form elements through [attr.name] = "formName" and [name] = "formName". If you have a complex validator, it is better to use a responsive form.

5. The template-driven form validator supports attribute binding and dynamically controls whether validation is required.

If a form element (such as a user name) is required is not certain, but dynamically set, in Angular through attribute binding-[required] = "isRequired"-very convenient control, I took a look at the Angular.js source code is now supported, I do not know whether I did not find it before or after the version added the function.

6. Support for asynchronous validators

If you want to verify that the user name input already exists, you need to request API remote authentication, then the validation is asynchronous, and if the validator does not support async, it will cause the form to be submitted directly when the verification result is not returned. It will be more perfect if it supports asynchrony.

Of course, the Angular form is not only the above functions, through our recent use, the Angular form is basically perfect, but

We also need to make validation error prompts more simple and extensible

Looking back, the introduction form at the beginning should contain the following three parts of functions

1. Collect the user's input form data; this basically ngModel two-way binding syntax candy has been simplified can no longer be simplified, of course, the use of responsive forms can not even write ngModel, this piece does not need developers to do anything

two。 Built-in validators meet most scenarios, but there are still many commonly used validators that are not officially provided, such as repeated validation, remote unique verification and so on. The two third-party libraries, Nightapes/ngx-validators and gangachris/ng-validators, have expanded a lot, even if they do not meet their own expansion.

3. Give feedback to the user after verification, and verify that the error message is not given. For this error message, each product each user will have different needs, Angular can do, automatically add ng-invalid, ng-valid, ng-touched and other class, and which elements which validator verification failure can be easily obtained from ngModel and ngForm, error tips can only be left to the user to deal with, if your system only has style feedback, it will be even easier.

For verification error prompts, the template for manually writing error prompts will be very verbose, and it's okay to write the template itself. I'm afraid that one day the designer will change the demand, and the original prompt method will be changed in a new way, then the whole system needs to be replaced one by one. what aspiring programmers fear most is to do repetitive work without content, and sometimes it can't be done through batch replacement. So in the use of Angular.js 1.x when I encapsulated a form verification library why520crazy/angular-w5c-validator, at the beginning of the release, the function is relatively simple, and then someone mentioned a variety of Issue, gradually improved, I think this verification library is helpful for many people, at least I think it is more elegant to deal with a variety of error tips, star is not much, but proved that this encapsulation still has a certain value.

So even if we upgrade to Angular now, we still face the problem of how to deal with errors. Of course, there are some class libraries that deal with related problems, but they don't seem to find anything particularly useful.

1. UltimateAngular/ngx-errors is still a handwritten template, but it simplifies the writing method.

2. NG-ZORRO/ng-zorro-antd component library has also done a lot of work on form components for error verification prompts, but still requires handwritten template configuration.

Since there is no relevant class library to meet our needs, it is obvious that we need to build our own wheels, so when we upgraded Angular last year, we added similar components to the Form form module of the component library in our way, thanks to the excellent Angular framework, it is very easy to build wheels.

Ngx-validator is ready to use.

So this week I extracted the form validation function as a separate class library why520crazy/ngx-validator, if you are also worried about form validation error prompts, but also looking for a more elegant error handling, I hope my library can help you or give you an inspiration.

At this point, I believe you have a deeper understanding of "how to use Angular form validation elegantly". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 237

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report