博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript中的基本表单验证
阅读量:2519 次
发布时间:2019-05-11

本文共 4639 字,大约阅读时间需要 15 分钟。

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代码:

  Form Validation    
Username
Email Address

基本验证 (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 :

考虑到这一点,也许开发人员使用正则表达式来确定电子邮件地址是否有效。 这是的功能:

const emailIsValid = email => {  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);}emailIsValid('free@code@camp.org') // falseemailIsValid('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)

翻译自:

转载地址:http://alrwd.baihongyu.com/

你可能感兴趣的文章
1.1 Friday the Thirteenth
查看>>
VS 高亮显示不带后缀的C++头文件
查看>>
python基础之面向对象
查看>>
Abnormal build process termination--解决IDEA启动web项目报错
查看>>
JS设计模式之工厂模式
查看>>
Git忽略规则及.gitignore规则不生效的解决办法
查看>>
EasyUI 搜索框
查看>>
impdp and docker install oracleXE
查看>>
入门训练 序列求和
查看>>
web前端_Vue框架_设置浏览器上方的标题和图标
查看>>
gnome3 隐藏标题栏
查看>>
duilib入门简明教程 -- 第一个程序 Hello World(3) (转)
查看>>
Visual Studio 2008下载
查看>>
hdu1712: ACboy needs your help
查看>>
[30期] 贫嘴漫谈时间
查看>>
远程连接工具SSH和linux的连接
查看>>
WPF 自定义依赖属性
查看>>
Android之Log封装
查看>>
立方体
查看>>
Python装饰器之 property()
查看>>