如何使用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/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392008.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392008.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392008.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數學哲學與科學哲學和計算機科學的能動作用,數學哲學與科學哲學和計算機科學的能動作用...

3 數學哲學與計算機科學的能動作用數學哲學對于計算機科學的影響主要表現于以下的事實:一些源于數學哲學(數學基礎研究)的概念和理論在計算機科學的歷史發展中發揮了十分重要的作用。例如,在此可以首先提及(一階)謂詞演算理論:這是由弗雷格(…

AngularDart4.0 指南- 表單

2019獨角獸企業重金招聘Python工程師標準>>> 表單是商業應用程序的主流。您可以使用表單登錄,提交幫助請求,下訂單,預訂航班,安排會議,并執行無數其他數據錄入任務。 在開發表單時,創建一個數據…

(轉載)分享常用的GoLang包工具

分享常用的GoLang包工具 包名 鏈接地址 備注 Machinery異步隊列 https://github.com/RichardKnop/machinery Mqtt通信 github.com/eclipse/paho.mqtt.golang go文檔http://www.eclipse.org/paho/clients/golang/ 微信開發 https://github.com/chanxuehong/wechat fasthttp包 gi…

邁向數據科學的第一步:在Python中支持向量回歸

什么是支持向量回歸? (What is Support Vector Regression?) Support vector regression is a special kind of regression that gives you some sort of buffer or flexibility with the error. How does it do that ? I’m going to explain it to you in simpl…

js 觸發LinkButton點擊事件,執行后臺方法

頁面 <asp:LinkButton ID"lbtButton" runat"server" CssClass"lbtButton" Font-Underline"false" OnClick"lbtButton_Click"> js function clickButton(filePath, fileName){ __doPostBack(lbtButton, ); } 當執行該…

vue 響應式ui_如何在Vue.js中設置響應式UI搜索

vue 響應式uiAre you thinking of building something awesome with one of the popular modern frameworks out there right now, but don’t know how to get started?您是否正在考慮使用當前流行的現代框架之一來構建出色的東西&#xff0c;但不知道如何入門&#xff1f; …

蘭州交通大學計算機科學與技術學院,蘭州交通大學

信息與計算科學專業依托數學和計算機科學與技術兩個一級學科碩士學位授予點&#xff0c;運籌學與控制論、計算機科學與技術兩個省級重點學科&#xff0c;培養理工融合、學科交叉的創新性人才。自2008年以來&#xff0c;承擔國家自然科學基金10余項&#xff0c;發表SCI收錄雜志論…

leetcode 424. 替換后的最長重復字符(滑動窗口)

給你一個僅由大寫英文字母組成的字符串&#xff0c;你可以將任意位置上的字符替換成另外的字符&#xff0c;總共可最多替換 k 次。在執行上述操作后&#xff0c;找到包含重復字母的最長子串的長度。 注意&#xff1a;字符串長度 和 k 不會超過 104。 示例 1&#xff1a; 輸入…

javascript放在head和body的區別(w3c建議放在head標簽中)

JavaScript腳本放在哪里 在HTML body部分中的JavaScripts會在頁面加載的時候被執行。 在HTML head部分中的JavaScripts會在被調用的時候才執行。—————————————————————————— JavaScript應放在哪里 頁面中的JavaScripts會在瀏覽器加載頁面的時候被立即…

jQuery事件整合

一、jQuery事件 1、focus&#xff08;&#xff09;元素獲得焦點 2、blur&#xff08;&#xff09;元素失去焦點 3、change&#xff08;&#xff09; 表單元素的值發生變化&#xff08;可用于驗證用戶名是否存在&#xff09; 4、click&#xff08;&#xff09; 鼠標單擊 5、dbc…

tableau跨庫創建并集_刮擦柏林青年旅舍,并以此建立一個Tableau全景。

tableau跨庫創建并集One of the coolest things about making our personal project is the fact that we can explore topics of our own interest. On my case, I’ve had the chance to backpack around the world for more than a year between 2016–2017, and it was one…

策略模式下表單驗證

策略模式下表單驗證 class Validator {constructor(strategies) {this.cache []}add(value, rules) {if (!rules instanceof Array) throw rules should be Arrayvar self thisfor(var i 0, rule; rule rules[i];) {(function(rule) {var strategyArr rule.strategy.split…

在五分鐘內學習使用Python進行類型轉換

by PALAKOLLU SRI MANIKANTA通過PALAKOLLU SRI MANIKANTA 在五分鐘內學習使用Python進行類型轉換 (Learn typecasting in Python in five minutes) 以非常詳盡的方式介紹了Python中的類型轉換和類型轉換的速成課程 (A crash course on Typecasting and Type conversion in Pyt…

Ajax post HTML 405,Web API Ajax POST向返回 405方法不允許_jquery_開發99編程知識庫

因此&#xff0c;我有一個像這樣的jquery ajax請求&#xff1a;function createLokiAccount(someurl) {var d {"Jurisdiction":17}$.ajax({type:"POST",url:"http://myserver:111/Api/V1/Customers/CreateCustomer/",data: JSON.stringify(d),c…

leetcode 480. 滑動窗口中位數(堆+滑動窗口)

中位數是有序序列最中間的那個數。如果序列的大小是偶數&#xff0c;則沒有最中間的數&#xff1b;此時中位數是最中間的兩個數的平均數。 例如&#xff1a; [2,3,4]&#xff0c;中位數是 3 [2,3]&#xff0c;中位數是 (2 3) / 2 2.5 給你一個數組 nums&#xff0c;有一個大…

1.0 Hadoop的介紹、搭建、環境

HADOOP背景介紹 1.1 Hadoop產生背景 HADOOP最早起源于Nutch。Nutch的設計目標是構建一個大型的全網搜索引擎&#xff0c;包括網頁抓取、索引、查詢等功能&#xff0c;但隨著抓取網頁數量的增加&#xff0c;遇到了嚴重的可擴展性問題——如何解決數十億網頁的存儲和索引問題。20…

如何實現多維智能監控?--AI運維的實踐探索【一】

作者丨吳樹生&#xff1a;騰訊高級工程師&#xff0c;負責SNG大數據監控平臺建設。近十年監控系統開發經驗&#xff0c;具有構建基于大數據平臺的海量高可用分布式監控系統研發經驗。 導語&#xff1a;監控數據多維化后&#xff0c;帶來新的應用場景。SNG的哈勃多維監控平臺在完…

.Net Web開發技術棧

有很多朋友有的因為興趣&#xff0c;有的因為生計而走向了.Net中&#xff0c;有很多朋友想學&#xff0c;但是又不知道怎么學&#xff0c;學什么&#xff0c;怎么系統的學&#xff0c;為此我以我微薄之力總結歸納寫了一篇.Net web開發技術棧&#xff0c;以此幫助那些想學&#…

使用Python和MetaTrader在5分鐘內開始構建您的交易策略

In one of my last posts, I showed how to create graphics using the Plotly library. To do this, we import data from MetaTrader in a ‘raw’ way without automation. Today, we will learn how to automate this process and plot a heatmap graph of the correlation…

卷積神經網絡 手勢識別_如何構建識別手語手勢的卷積神經網絡

卷積神經網絡 手勢識別by Vagdevi Kommineni通過瓦格德維科米尼(Vagdevi Kommineni) 如何構建識別手語手勢的卷積神經網絡 (How to build a convolutional neural network that recognizes sign language gestures) Sign language has been a major boon for people who are h…