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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值