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.mzph.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并执行预测。 此功能…