JavaScript中的基本表單驗證

In the past, form validation would occur on the server, after a person had already entered in all of their information and pressed the submit button.

過去,表單驗證會在一個人已經輸入了所有信息并按下“提交”按鈕之后在服務器上進行。

If the information was incorrect or missing, the server would have to send everything back with a message telling the person to correct the form before submitting it again.

如果信息不正確或丟失,服務器將必須將所有內容發送回去,并帶有一條消息,告知該人在重新提交表單之前先進行更正。

This was a lengthy process and would put a lot of the burden on the server.

這是一個漫長的過程,將給服務器帶來很多負擔。

These days, JavaScript provides a number of ways to validate a form's data right in the browser before sending it to the server.

如今,JavaScript提供了多種方法,可以在將表單數據發送到服務器之前直接在瀏覽器中對其進行驗證。

Here's the HTML code we'll use in the following examples:

這是我們在以下示例中使用HTML代碼:

<html>
<head><title>Form Validation</title><script type="text/javascript">// Form validation will go here</script>
</head>
<body><form id="form"><table cellspacing="2" cellpadding="2" border="1"><tr><td align="right">Username</td><td><input type="text" id="username" /></td></tr><tr><td align="right">Email Address</td><td><input type="text" id="email-address" /></td></tr><tr><td></td><td><input type="submit" value="Submit" id="submit-btn" /></td></tr></table></form>
</body>
</html>

基本驗證 (Basic Validation)

This type of validation involves checking all the mandatory fields and making sure they're properly filled in.

這種類型的驗證涉及檢查所有必填字段,并確保已正確填寫它們。

Here's a basic example of a function validate that shows an alert if the username and email address inputs are blank, otherwise it returns true:

這是一個功能validate的基本示例,如果用戶名和電子郵件地址輸入為空,則顯示警報,否則返回true:

const submitBtn = document.getElementById('submit-btn');const validate = (e) => {e.preventDefault();const username = document.getElementById('username');const emailAddress = document.getElementById('email-address');if (username.value === "") {alert("Please enter your username.");username.focus();return false;}if (emailAddress.value === "") {alert("Please enter your email address.");emailAddress.focus();return false;}return true;
}submitBtn.addEventListener('click', validate);

But what if someone enters in random text as their email address? Currently the validate function will still return true. As you can imagine, sending bad data to the server can lead to problems.

但是,如果有人輸入隨機文本作為其電子郵件地址怎么辦? 當前, validate函數將仍然返回true。 可以想象,將錯誤的數據發送到服務器可能會導致問題。

That's where data format validation comes in.

這就是數據格式驗證的地方。

數據格式驗證 (Data Format Validation)

This type of validation actually looks at the values in the form and verifies that they are correct.

這種類型的驗證實際上會查看表單中的值并驗證它們是否正確。

Validating email addresses is notoriously difficult – there are a vast number of legitimate email addresses and hosts, and it's impossible to guess all the valid combinations of characters.

眾所周知,驗證電子郵件地址非常困難-有大量合法的電子郵件地址和主機,并且不可能猜測所有有效的字符組合。

That said, there are a few key factors that are common in all valid email addresses:

就是說,所有有效電子郵件地址中都有一些共同的關鍵因素:

  • An address must contain one @ and at least one dot (.) character

    一個地址必須包含一個@和至少一個點(。)字符
  • The @ character cannot be the first character in the address

    @字符不能是地址中的第一個字符
  • The . must come at least one character after the @ character

    的。 必須在@字符之后至少一個字符

With this in mind, maybe developers use regex to determine if an email address is valid or not. Here's a function that Tyler McGinnis recommends on his blog:

考慮到這一點,也許開發人員使用正則表達式來確定電子郵件地址是否有效。 這是Tyler McGinnis在他的博客上推薦的功能:

const emailIsValid = email => {return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}emailIsValid('free@code@camp.org') // false
emailIsValid('quincy@freecodecamp.org') // true

Added to the code from the last example, it will look like this:

將其添加到上一個示例的代碼中后,它將如下所示:

const submitBtn = document.getElementById('submit-btn');const validate = (e) => {e.preventDefault();const username = document.getElementById('username');const emailAddress = document.getElementById('email-address');if (username.value === "") {alert("Please enter your username.");username.focus();return false;}if (emailAddress.value === "") {alert("Please enter your email address.");emailAddress.focus();return false;}if (!emailIsValid(emailAddress.value)) {alert("Please enter a valid email address.");emailAddress.focus();return false;}return true; // Can submit the form data to the server
}const emailIsValid = email => {return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}submitBtn.addEventListener('click', validate);

HTML5表單約束 (HTML5 Form Constraints)

Some of commonly used HTML5 constraints for <input> are the type attribute (e.g. type="password"), maxlength, required and disabled.

<input>一些常用HTML5約束是type屬性(例如type="password" ), maxlengthrequireddisabled

A less commonly used constraint is the pattern attribute that takes a JavaScript regular expression.

較少使用的約束是采用JavaScript正則表達式的pattern屬性。

更多信息 (More Information)

  • Form Data Validation | MDN

    表格數據驗證| MDN

  • Constraint validation | MDN

    約束驗證| MDN

翻譯自: https://www.freecodecamp.org/news/basic-form-validation-in-javascript/

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

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

相關文章

leetcode 877. 石子游戲(dp)

題目 亞歷克斯和李用幾堆石子在做游戲。偶數堆石子排成一行&#xff0c;每堆都有正整數顆石子 piles[i] 。 游戲以誰手中的石子最多來決出勝負。石子的總數是奇數&#xff0c;所以沒有平局。 亞歷克斯和李輪流進行&#xff0c;亞歷克斯先開始。 每回合&#xff0c;玩家從行的…

es6的Map()構造函數

普通的object對象是鍵值對的集合&#xff0c;但對于它的鍵卻有著嚴苛的要求&#xff0c;必須是字符串&#xff0c;這給我們平時帶來很多的不方便 Map函數類似于對象&#xff0c;但它是一個更加完美的簡直對集合&#xff0c;鍵可以是任意類型 set()方法可以向map實例對象中添加一…

mac里打開隱藏的 library文件夾

打開Finder&#xff0c;單擊【前往】&#xff0c;此時只有按住【option】鍵&#xff0c;就能出現“資源庫”的選項。 或者鍵入 ~/Library 進入 轉載于:https://www.cnblogs.com/laolinghunWbfullstack/p/8888124.html

華為開源構建工具_為什么我構建了用于大數據測試和質量控制的開源工具

華為開源構建工具I’ve developed an open-source data testing and a quality tool called data-flare. It aims to help data engineers and data scientists assure the data quality of large datasets using Spark. In this post I’ll share why I wrote this tool, why …

字號與磅值對應關系_終極版式指南:磅值,大寫與小寫,Em和En破折號等

字號與磅值對應關系Typography is a field that deals with the written word and how letters and characters are presented.印刷術是處理文字以及字母和字符的顯示方式的領域。 The same letters can be styled in different ways to convey different emotions. And there…

leetcode 65. 有效數字(正則表達式)

題目 有效數字&#xff08;按順序&#xff09;可以分成以下幾個部分&#xff1a; 一個 小數 或者 整數 &#xff08;可選&#xff09;一個 ‘e’ 或 ‘E’ &#xff0c;后面跟著一個 整數 小數&#xff08;按順序&#xff09;可以分成以下幾個部分&#xff1a; &#xff08;…

Swift中的閉包例子

常見的實現&#xff0c; 要熟悉了解&#xff0c; 至于閉包逃逸&#xff0c; 自動閉包這些內容&#xff0c; 可以以后用到時再學吧。 let names ["Chris", "Alex", "Eva", "Barry", "Daniella"]func backward(_ s1: String,…

如何判斷自己的編程水平

有的朋友說&#xff1a;當一段時間后的你&#xff0c;再重新看回以前寫的代碼&#xff0c;會覺得很渣&#xff0c;就證明你有學到新東西了。轉載于:https://www.cnblogs.com/viplued/p/7943405.html

數據科學項目_完整的數據科學組合項目

數據科學項目In this article, I would like to showcase what might be my simplest data science project ever.在本文中&#xff0c;我想展示一下有史以來最簡單的數據科學項目 。 I have spent hours training a much more complex models in the past, and struggled to …

回溯算法和貪心算法_回溯算法介紹

回溯算法和貪心算法回溯算法 (Backtracking Algorithms) Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably constraint satisfaction problems. It incrementally builds candidates to the solutions, and …

alpha沖刺day8

項目進展 李明皇 昨天進展 編寫完個人中心頁面今天安排 編寫首頁邏輯層問題困難 開始編寫數據傳遞邏輯&#xff0c;要用到列表渲染和條件渲染心得體會 小程序框架設計的內容有點忘了&#xff0c;而且比較抽象&#xff0c;需要理解文檔舉例和具體案例林翔 昨天進展 黑名單用戶的…

增加 processon 免費文件數

github 地址&#xff1a;github.com/96chh/Upgra… 關于 ProcessOn 非常好用的思維導圖網站&#xff0c;不僅支持思維導圖&#xff0c;還支持流程圖、原型圖、UML 等。比我之前用的百度腦圖強多了。 直接登錄網站就可以編輯&#xff0c;非常適合我在圖書館公用電腦學習使用。 但…

uni-app清理緩存數據_數據清理-從哪里開始?

uni-app清理緩存數據It turns out that Data Scientists and Data Analysts will spend most of their time on data preprocessing and EDA rather than training a machine learning model. As one of the most important job, Data Cleansing is very important indeed.事實…

高級人工智能之群體智能:蟻群算法

群體智能 鳥群&#xff1a; 魚群&#xff1a; 1.基本介紹 蟻群算法&#xff08;Ant Colony Optimization, ACO&#xff09;是一種模擬自然界螞蟻覓食行為的優化算法。它通常用于解決路徑優化問題&#xff0c;如旅行商問題&#xff08;TSP&#xff09;。 蟻群算法的基本步驟…

JavaScript標準對象:地圖

The Map object is a relatively new standard built-in object that holds [key, value] pairs in the order that theyre inserted. Map對象是一個相對較新的標準內置對象&#xff0c;按插入順序保存[key, value]對。 The keys and values in the Map object can be any val…

leetcode 483. 最小好進制

題目 對于給定的整數 n, 如果n的k&#xff08;k>2&#xff09;進制數的所有數位全為1&#xff0c;則稱 k&#xff08;k>2&#xff09;是 n 的一個好進制。 以字符串的形式給出 n, 以字符串的形式返回 n 的最小好進制。 示例 1&#xff1a; 輸入&#xff1a;“13” 輸…

圖像灰度變換及圖像數組操作

Python圖像灰度變換及圖像數組操作 作者&#xff1a;MingChaoSun 字體&#xff1a;[增加 減小] 類型&#xff1a;轉載 時間&#xff1a;2016-01-27 我要評論 這篇文章主要介紹了Python圖像灰度變換及圖像數組操作的相關資料,需要的朋友可以參考下使用python以及numpy通過直接操…

npx npm區別_npm vs npx —有什么區別?

npx npm區別If you’ve ever used Node.js, then you must have used npm for sure.如果您曾經使用過Node.js &#xff0c;那么一定要使用npm 。 npm (node package manager) is the dependency/package manager you get out of the box when you install Node.js. It provide…

找出性能消耗是第一步,如何解決問題才是關鍵

作者最近剛接手一個新項目&#xff0c;在首頁列表滑動時就感到有點不順暢&#xff0c;特別是在滑動到有 ViewPager 部分的時候&#xff0c;如果是熟悉的項目&#xff0c;可能會第一時間會去檢查代碼&#xff0c;但前面說到這個是剛接手的項目&#xff0c;同時首頁的代碼邏輯比較…

bigquery_如何在BigQuery中進行文本相似性搜索和文檔聚類

bigqueryBigQuery offers the ability to load a TensorFlow SavedModel and carry out predictions. This capability is a great way to add text-based similarity and clustering on top of your data warehouse.BigQuery可以加載TensorFlow SavedModel并執行預測。 此功能…