如何使用JavaScript检查输入是否为空

by Zell Liew

由Zell Liew

如何使用JavaScript检查输入是否为空 (How to check if an input is empty with JavaScript)

Last week, I shared how to check if an input is empty with CSS. Today, let’s talk about the same thing, but with JavaScript.

上周,我分享了如何使用CSS检查输入是否为空 。 今天,让我们谈谈同一件事,但使用JavaScript。

It’s much simpler.

这要简单得多。

Here’s what we’re building:

这是我们正在构建的:

验证输入的事件 (Events to validate the input)

If you want to validate the input when a user types into the field, you can use the input event.

如果要在用户在字段中键入内容时验证输入,则可以使用input事件。

const input = document.querySelector('input')input.addEventListener('input', evt => {  // Validate input})

If you want to validate the input when a user submits a form, you can use the submit event. Make sure you prevent the default behavior withpreventDefault.

如果要在用户提交表单时验证输入,则可以使用submit事件。 确保使用preventDefault防止默认行为。

If you don’t prevent the default behavior, browsers will navigate the user to the URL stated in the action attribute.

如果您不阻止默认行为,浏览器将把用户导航到action属性中指定的URL。

const form = document.querySelector('form')form.addEventListener('submit', evt => {  evt.preventDefault()
// Validate input})

验证输入 (Validating the input)

We want to know whether an input is empty. For our purpose, empty means:

我们想知道输入是否为空。 就我们的目的而言,空表示:

  1. The user hasn’t typed anything into the field

    用户尚未在该字段中输入任何内容
  2. The user has typed one or more empty spaces, but not other characters

    用户键入了一个或多个空格,但没有键入其他字符

In JavaScript, the pass/fail conditions can be represented as:

在JavaScript中,通过/失败条件可以表示为:

// Empty' ''  ''   '
// Filled'one-word''one-word '' one-word'' one-word ''one phrase with whitespace''one phrase with whitespace '' one phrase with whitespace'' one phrase with whitespace '

Checking this is easy. We just need to use the trim method. trim removes any whitespace from the front and back of a string.

检查很容易。 我们只需要使用trim方法。 trim删除字符串前后的所有空格。

const value = input.value.trim()

If the input is valid, you can set data-state to valid. If the input is invalid, you can set the data-state to invalid.

如果输入有效,则可以将data-state设置为valid 。 如果输入无效,则可以将data-state设置为invalid

// This is JavaScript
input.addEventListener('input', evt => {  const value = input.value.trim()
if (value) {    input.dataset.state = 'valid'  } else {    input.dataset.state = 'invalid'  }})
/* This is CSS */
/* Show red borders when filled, but invalid */input[data-state="invalid"] {  border-color: hsl(0, 76%, 50%);}
/* Show green borders when valid */input[data-state="valid"] {  border-color: hsl(120, 76%, 50%);}This isn’t the end yet. We have a problem.

When a user enters text into the field, input validation begins. However, if the user removes all text from the field, the input continues to be invalid.

当用户在字段中输入文本时,输入验证开始。 但是,如果用户从字段中删除了所有文本,则输入将继续无效。

We don’t want to invalidate the input if the user removes all text. They may need a moment to think, but the invalidated state sets off an unnecessary alarm.

如果用户删除了所有文本,我们不想使输入无效。 他们可能需要花点时间思考,但是无效状态会引发不必要的警报。

To fix this, we can check whether the user has entered any text into the input before we trim it.

要解决此问题,我们可以在trim之前检查用户是否在输入中输入了任何文本。

input.addEventListener('input', evt => {  const value = input.value
if (!value) {    input.dataset.state = ''    return  }
const trimmed = value.trim()
if (trimmed) {    input.dataset.state = 'valid'  } else {    input.dataset.state = 'invalid'  }})

Here’s a Codepen for you to play with:

这是一个Codepen供您使用:

See the Pen Empty validation with JavaScript by Zell Liew (@zellwk) on CodePen.

见笔用JavaScript空验证通过泽尔与Liew( @zellwk )上CodePen

Thanks for reading. Did this article help you out? If it did, I hope you consider sharing it. You might help someone else out. Thanks so much!

谢谢阅读。 这篇文章对您有帮助吗? 如果确实如此,希望您考虑共享它 。 您可能会帮助别人。 非常感谢!

This article was originally posted at my blog.Sign up for my newsletter if you want more articles to help you become a better frontend developer.

本文最初发布在我的博客上 如果您想获得更多文章来帮助您成为更好的前端开发人员,请注册我的时事通讯

翻译自: https://www.freecodecamp.org/news/checking-if-an-input-is-empty-with-javascript-d41ed5a6195f/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值