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"
), maxlength
, required
和disabled
。
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/