angular和react_如何在Angular中驗證默認和自定義React形式

angular和react

by Luuk Gruijs

Luuk Gruijs著

如何在Angular中驗證默認和自定義React形式 (How to validate default and custom reactive forms in Angular)

When presenting forms to your users, it’s considered very user-friendly to give them immediate feedback on whether what they type is actually correct. Besides that, it could also limit the number of requests to the server. You would be able to catch 99% of the errors before submitting your form to the server.

向您的用戶展示表單時,認為他們非常友好,可以立即向他們反饋輸入的內容是否正確。 除此之外,它還可能限制對服務器的請求數量。 在將表單提交到服務器之前,您將能夠捕獲99%的錯誤。

When using reactive forms, Angular offers only a hand full of very generic validators. The default form field validators are:

當使用React形式時,Angular僅提供一堆非常通用的驗證器。 默認的表單字段驗證器為:

  • min: the value should be higher than a certain number.

    min:該值應大于一定數值。

  • max: the value should be lower than a certain number.

    max:該值應小于一定數值。

  • required: the value cannot be empty

    必填:值不能為空

  • requiredTrue: the value must be true

    requiredTrue:該值必須為true

  • email: the value should be an email

    電子郵件:值應為電子郵件

  • minLength: The value should contain a minimum amount of characters

    minLength:該值應包含最少數量的字符

  • maxLength: The value should contain a maximum amount of characters

    maxLength:該值應包含最大字符數

Chances are the above validators will not be able to match the requirements of your server. Therefore you cannot give the user the feedback they would like to get and help them submit a correct form. For this, you are going to need custom form field validators.

上述驗證器很可能無法滿足您服務器的要求。 因此,您無法向用戶提供他們希望獲得的反饋并無法幫助他們提交正確的表單。 為此,您將需要自定義表單字段驗證器。

創建自定義表單字段驗證器 (Creating a custom form field validator)

A form field validator is a function that takes your form control — the input field — and validates the value of that form control against a certain condition. This function either returns nothing when everything is ok or an object stating what went wrong.

表單字段驗證器是一種功能,它接受您的表單控件(即輸入字段),并針對特定條件驗證該表單控件的值。 一切正常時,此函數不返回任何內容,或者一個對象指出發生了什么問題。

A very common use case of a custom validator is to check whether the form matches the sanitization rules of the server. This means the validator checks if the characters your user puts into your form are allowed. Let’s create this form validator now.

定制驗證器的一個非常常見的用例是檢查表單是否與服務器的清理規則匹配。 這意味著驗證器檢查是否允許用戶輸入您的表單中的字符。 讓我們現在創建此表單驗證器。

建立表格 (Building the form)

To use this validator we need to create a form and define it there. For this purpose, we’re going to create a simple user signup form. We use the reactive way to create the form. It can be done like this:

要使用此驗證器,我們需要創建一個表單并在其中定義它。 為此,我們將創建一個簡單的用戶注冊表單。 我們使用React方式來創建表單。 可以這樣完成:

The template can then look like this:

模板可以如下所示:

We now have a working reactive form. We, however, did not apply any form validation. To add form validation, we simply pass our validators into the form creation function like this:

現在,我們有了一個有效的React形式。 但是,我們沒有應用任何表單驗證。 要添加表單驗證,我們只需將驗證器傳遞給表單創建函數,如下所示:

We used the required and email validators from Angular. We also imported our custom created validateCharacters validator. The last thing we still have to do is present potential errors to our users.

我們使用了來自Angular的必需驗證器和電子郵件驗證器。 我們還導入了自定義創建的validateCharacters驗證器。 我們仍然要做的最后一件事是向我們的用戶展示潛在的錯誤。

向用戶呈現錯誤 (Presenting errors to the user)

There are two moments when we want to present errors to our users: when the focus moves from one field to the other and right before the final form submission.

我們有兩個時刻要向用戶展示錯誤:焦點從一個字段移到另一個字段,并且恰好在提交最終表單之前。

Let’s create a form service for this. This service could potentially look like this:

讓我們為此創建一個表單服務。 該服務可能看起來像這樣:

The validateForm method accepts the form to validate, a form errors object and a boolean on whether to check dirty fields or not. The function then loops over all the form controls and checks if there are errors on that control. If there are any, we find the correct error message that came from the validationMessages method and pass back the form errors object.

validateForm方法接受要驗證的表單,一個表單錯誤對象以及一個是否檢查臟字段的布爾值。 然后,該函數循環遍歷所有窗體控件,并檢查該控件上是否有錯誤。 如果有任何錯誤消息,我們將找到來自validationMessages方法的正確錯誤消息,并將其傳遞給表單錯誤對象。

To use this error service in our components, we have to do the following:

要在我們的組件中使用此錯誤服務,我們必須執行以下操作:

Now the final step is to show the error messages in our template. We can do that like this:

現在,最后一步是在模板中顯示錯誤消息。 我們可以這樣做:

If there any errors on one particular field, we show the message that’s in the formErrors object. Below is a full demo. Play around with the fields. Try to fill in characters like !#$^ in the name field and see if our custom form validator works. If no errors appear, hit the signup button and see the success message.

如果在一個特定字段上有任何錯誤,我們將顯示formErrors對象中的消息。 以下是完整的演示。 在田野里玩。 嘗試在名稱字段中填寫!#$^類的字符,并查看我們的自定義表單驗證程序是否有效。 如果沒有錯誤出現,請點擊注冊按鈕,查看成功消息。

結論 (Conclusion)

I hope this article helps you validate your forms and give your users a better experience when filling in the forms.

我希望本文能幫助您驗證表單并在填寫表單時為用戶提供更好的體驗。

在阿姆斯特丹找工作? (Looking for a job in Amsterdam?)

I work for Sytac as a Senior front-end developer. We are looking for mid/senior developers that specialize in Angular, React, Java or Scala. Sytac is a very ambitious consultancy company in the Netherlands.

我在Sytac擔任高級前端開發人員。 我們正在尋找專門從事Angular,React,Java或Scala的中/高級開發人員。 Sytac是荷蘭一家雄心勃勃的咨詢公司。

If you think you have what it takes to work with the best, send me an email on luuk.gruijs@sytac.io and I’m happy to tell you more.

如果您認為自己有最佳的工作條件,請給我發送電子郵件至luuk.gruijs@sytac.io ,我很樂意告訴您更多信息。

翻譯自: https://www.freecodecamp.org/news/validating-reactive-forms-with-default-and-custom-form-field-validators-in-angular-5586dc51c4ae/

angular和react

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395589.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395589.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395589.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

POJ 1502 MPI Maelstrom 最短路

最短路模板。 題意:從‘1’點發出一個信號到各個點,不同的點可以同時發出一個信號但到達目標的時間不同,問所有點接受到信號所耗費的最短時間為多少。 思路:迪杰斯特拉求出1點到各個點的最短路,遍歷一遍找到其中的最大…

調試dump文件

調試dump文件 1、設置好pdb文件和源代碼路徑 為了能正確分析Dump文件,我們必須要指定和程序一起出來的PDB文件,如果程序重新被編譯了一次,即使代碼沒有任何變化,之前的PDB文件我們不能再繼續使用。posted on 2018-12-28 17:50 mao…

不一樣的視角,程序員世界里的環保

摘要: 我們身邊有很多可以做的技術環保工作。比如說,在Linux下少用root用戶,SQL的時候,delete前先select,這樣,你就不會做出一些讓你后悔的事。不會讓你重頭來過,從而至少不會浪費電能。寫代碼的…

oracle查出連續5行,Oracle期末考試復習題2

復習題一、填空題:1. Oracle EnterpriseManager是一個基于 B/S的框架系統。2.Oracle數據庫的存儲結構分為物理結構和邏輯結構。3.在游標或者游標變量打開后還沒有進行第一次提取時,%found屬性為null。4. 在oracle中已c…

selinux會阻礙掛載嘛_為什么追求完美可能會阻礙您成為新手Web開發人員

selinux會阻礙掛載嘛by Rick West由里克韋斯特(Rick West) 為什么追求完美可能會阻礙您成為新手Web開發人員 (Why striving for perfection might be holding you back as a newbie web developer) I am a perfectionist. Or, at least, I like to think I am. Either way, I’…

MySQL優化的一些基礎

在Apache, PHP, mysql的體系架構中,MySQL對于性能的影響最大,也是關鍵的核心部分。對于Discuz!論壇程序也是如此,MySQL的設置是否合理優化,直接 影響到論壇的速度和承載量!同時,MySQL也是優化難度最大的一個…

oracle 會話 lock,相克軍_Oracle體系_隨堂筆記014-鎖 latch,lock

1、Oracle鎖類型鎖的作用latch鎖:chain,鏈LOCK鎖排他鎖(X)共享鎖(S)2、行級鎖:DML語句事務鎖TX鎖的結構事務鎖的加鎖和解鎖過程只有排他鎖不影響讀(CR塊)3、表級鎖:TM行級排他鎖(Row exclusive)RX鎖當我們進行DML時,會…

電線之間:采訪Microsoft Edge性能PM Nolan Lawson

by Vivian Cromwell通過維維安克倫威爾(Vivian Cromwell) 電線之間:采訪Microsoft Edge性能PM Nolan Lawson (Between the Wires: An interview with Microsoft Edge performance PM Nolan Lawson) I interviewed Nolan Lawson, Web Performance PM at Microsoft E…

swift菜鳥入門視頻教程-09-類和結構體

本人自己錄制的swift菜鳥入門,歡迎大家拍磚,有什么問題能夠在這里留言。主要內容:類和結構體對照 結構體和枚舉是值類型 類是引用類型 類和結構體的選擇 集合(collection)類型的賦值與復制行為視頻地址:百度…

oracle的集合操作符,[Oracle] Oracle的集合操作符

Oracle的集合操作包括: union , intersect , minus.[例子]假設有兩個表a,b如下:SQL> select * from a;COLA----------123SQL> select * from b;COLB----------345union : 得到兩個結果集的并集(不含重復值)SQL> select * from a2 union3 select * from b;COLA------…

鎖大全與 GDB調試

1.innodb_lock_monitor:打開鎖信息的方式 mysql> create table innodb_lock_monitor(id int) engineInnoDB; Query OK, 0 rows affected, 1 warning (2.29 sec) mysql> begin work; Query OK, 0 rows affected (0.00 sec) mysql> update t set val val 1…

[筆試面試題] 8-面向對象篇

面向對象篇 1 面向對象與面向過程的含義以及區別? 面向對象 面向對象是把數據及對數據的操作方法放在一起,作為一個相互依存的整體,即對象。對同類對象抽象出其共性,即類,類中的大多數數據,只能被本類的方法…

管理員所有權代碼_為什么代碼所有權糟透了,您永遠不應該在有實踐的地方工作...

管理員所有權代碼Code ownership sucks.代碼所有權糟透了。 It limits code and stunts your growth as a developer.它限制了代碼并阻礙了您作為開發人員的成長。 Let’s look at what code ownership is and why it destroys individuals and organizations.讓我們看看什么…

AngularJS 自定義控件

AngularJS Custom Directives 好討厭不帶日期的博客,而且說得好啰嗦 自定義指令介紹 AngularJS 指令作用是在 AngulaJS 應用中操作 Html 渲染。比如說,內插指令 ( {{ }} ), ng-repeat 指令以及 ng-if 指令。 當然你也可以實現自己的。這就是 AngularJS 所…

oracle 監聽加密 tcps,通過oracle wallet配置listener tcps加密

一 配置客戶端和服務端的wallet2端配置方法一致,相互添加證書orapki wallet create -wallet "/u01/oracle/wallet" -pwd Wdkf984jkkgekj434FKFD -auto_login_localorapki wallet add -wallet "/u01/oracle/wallet" -pwd Wdkf984jkkgekj434FKFD …

[財務知識] debt debit credit 的區別于聯系

https://blog.csdn.net/sjpljr/article/details/70169303 劍橋詞典解釋分別為: Debt [C or U ] n.something, especially money, which is owed to someone else, or the state of owing something借款,欠款;債務He ran/got into debt ( borr…

SpringMVC視圖解析器

SpringMVC視圖解析器 前言 在前一篇博客中講了SpringMVC的Controller控制器,在這篇博客中將接著介紹一下SpringMVC視 圖解析器。當我們對SpringMVC控制的資源發起請求時,這些請求都會被SpringMVC的DispatcherServlet處理,接著 Spring會分析看…

TIOBE 10月編程語言排行榜 : GO 問鼎本年度語言 ?

距離2016年度編程語言的公布只剩3個月了,誰將奪得桂冠? 與去年同期相比,2016年只有Go語言和Groovy語言的增長率超過了1%。 需要注意的是,Groovy語言2015年以一個爆炸性增長的收尾,所以到2017年1月左右的增長速度可能不…

校友郵箱_freeCodeCamp校友網絡:FCC校友的自主指導網絡

校友郵箱by peterWeinberg彼得溫伯格 freeCodeCamp校友網絡:FCC校友的自主指導網絡 (The freeCodeCamp Alumni Network: A homegrown mentorship network for FCC alumni) For the last year, I’ve been spending nearly all my free time learning to code. I’v…

oracle severity,ORACLE10G如何清除OEM下的歷史警告信息

ORACLE10G如何清除OEM下的歷史警告信息問題描述:OEM的HOME頁面可以顯示ORACLE的報警信息,但報警事件清除后該信息不會自動清除。隨著時間的增長,信息量逐漸加大,解決方法是手工予以清除。SampleCluster DatabaseTablespaces FullT…