Css input empty value

How to Match an Empty Input Box with CSS

It is possible to match an empty input box only if the input field is required. In this case, you can use the :valid pseudo-class.

In our tutorial, you can see how to match an empty input box step by step. Let’s start with creating HTML.

Create HTML

form> input type="text" placeholder="Type something. " id="test" required="required"> span class="message">Some text span> form>

Add CSS

  • Set the visibility to «hidden» for the «message» class.
  • Add a :valid pseudo-class to the «test» and also add the «message» class. Then, set the visibility to «visible».
.message < visibility: hidden; > #test:valid+.message < visibility: visible; >

The result of our code looks like the following.

Читайте также:  Org apache commons logging logfactory java lang classnotfoundexception

Example of matching an empty input type:

html> html> head> title>The title of the document title> style> .message < visibility: hidden; > #test:valid+.message < visibility: visible; > style> head> body> form> input type="text" placeholder="Type something. " id="test" required="required"> span class="message">Some text span> form> body> html>

Result of matching an empty input box

Below, type something to see how the placeholder text is hidden.

BookDuck

Источник

Checking if an input is empty with CSS

Is it possible to know if an input is empty with only CSS?

I had that question when I tried to make an autocomplete component for Learn JavaScript. Basically, I wanted to:

  1. Hide a dropdown if the input is empty
  2. Show the dropdown if the input is filled

I found a way to do it. It’s not perfect. There are a few nuances involved, but I want to share it with you.

The form

First, let’s build a form so we’re on the same page. We’re going to use a simple form with one input.

form>  label for="input"> Input label>  input type="text" id="input" /> form>

When the input is filled, we want to change its border-color to green. Here’s an example of what we’re creating:

Checking if the input is empty

I relied on HTML form validation to check whether the input is empty. That meant I needed a required attribute.

form>  label> Input label>  input type="text" name="input" id="input" required /> form>

At this point, it works fine when the input is filled. Borders turned green.

But there’s a problem: If the user enters a whitespace into the field, the borders turn green too.

Technically, this is correct. The input is filled because the user typed something into it.

But I didn’t want whitespaces to trigger a blank dropdown menu (for the autocomplete component).

It wasn’t enough. I needed a more stringent check.

Further checks

HTML gives you the ability to validate inputs with regular expressions with the pattern attribute. I decided to test it out.

Since I didn’t want whitespaces to be recognized, I started with the \S+ pattern. This pattern meant: One or more characters that’s not a whitespace.

form>  label> Input label>  input type="text" name="input" id="input" required pattern="\S+" /> form>

Sure enough, it worked. If a user enters a whitespace into the field, the input doesn’t get validated.

But when a whitespace is entered (anywhere) into the input, the input gets invalidated.

Unfortunately, this pattern didn’t work in my use case.

In Learn JavaScript’s autocomplete component, I taught students how to complete a list of countries. The names of some countries had spaces…

I had to include whitespaces in the mix.

The next best alternative I could think of is \S+.* . This means 1 or more non-whitespace characters, followed by zero or more (any) characters.

form>  label> Input label>  input type="text" name="input" id="input" required pattern="\S+.*" /> form>

This worked! I can enter whitespaces into the mix now!

But there’s one more problem… the input doesn’t validate if you START with a whitespace…

And that’s the problem I couldn’t resolve. More on this later.

When I worked on this article, I came across another interesting question: Is it possible to style an invalid state when the input is filled incorrectly?

Invalidating the input

We don’t want to use :invalid because we’ll kickstart the input with an invalid state. (When the input is empty, it’s already invalid).

This is where Chris Coyier swooped in to the rescue with ” Form Validation UX in HTML and CSS“.

In the article, Chris talks about a :placeholder-shown pseudo-class. It can be used to check whether a placeholder is shown.

  1. You add a placeholder to your input
  2. If the placeholder is hidden, it means the user typed something into the field
  3. Proceed with validation (or invalidation)

Here’s the CSS (simplified version. For the complete version, check out Chris’s article)

/* Show red borders when filled, but invalid */ input:not(:placeholder-shown)  border-color: hsl(0, 76%, 50%); >

Since I had both validation AND invalidation styles, I had to ensure the valid styles came after the invalid styles.

/* Show red borders when filled, but invalid */ input:not(:placeholder-shown)  border-color: hsl(0, 76%, 50%); > /* Show green borders when valid */ input:valid  border-color: hsl(120, 76%, 50%); >

Here’s a demo for you to play with:

Note: Edge doesn’t support :placeholder-shown , so it’s probably not a good idea to use it in production yet. There’s no good way to detect this feature.

Now back to the problem I couldn’t resolve.

The problem with pattern

The pattern attribute is wonderful because it lets you accept a regular expression. This regular expression lets you validate the input with anything you can think of.

But… the regular expression must match the text completely. If the text doesn’t get matched completely, the input gets invalidated.

This created the problem I mentioned above. (Reminder of the problem: If a user enters a whitespace first, the input becomes invalid).

I couldn’t find a regular expression that worked for all use-cases that I thought of. If you want to try your hand at creating a regular expression that I need, I’d be more than welcome to receive the help!

// Should not match '' ' ' ' ' ' ' // Should match 'one-word' 'one-word ' ' one-word' ' one-word ' 'one phrase with whitespace' 'one phrase with whitespace ' ' one phrase with whitespace' ' one phrase with whitespace '

(Then again, I might be overthinking it… 🙄).

Update: Problem solved!

Many readers were generous enough to email me their solutions. I want to thank everyone who helped. Thank you so much!

The cleanest solution I received is: .*\S.* by Daniel O’Connor. This means:

  • .* : Any character
  • \S : Followed one non-whitespace character
  • .* : Followed by any character

Other regexes I received include:

Here’s a codepen with the updated solution by Daniel:

Wrapping up

Yes, it is possible to validate a form with pure CSS, but there are potential problems with validation when whitespace characters are involved.

If you don’t mind the whitespaces, it works perfectly. Have fun trying this pattern out! (Sorry, I can’t help it).

I hope you found this useful. If you did, I hope you’ll share it with someone else. And feel free to reach out if you have any questions or comments.

Thanks for reading, all the best, and happy coding!

Want to become a better Frontend Developer?

Don’t worry about where to start. I’ll send you a library of articles frontend developers have found useful!

I’ll also send you one article every week to help you improve your FED skills crazy fast!

Want to become a better Frontend Developer?

Don’t worry about where to start. I’ll send you a library of articles frontend developers have found useful!

I’ll also send you one article every week to help you improve your FED skills crazy fast!

© 2013 — 2023 Zell Liew. All rights reserved · Terms

Источник

Псевдоклассы :empty и :blank | Когда элемент пустой | CSS

Пустому элементу (тот, который не имеет вложенных потомков, в том числе пробелов и переносов строки Enter ), можно задать стиль с помощью псевдокласса :empty [w3.org]. Элементу, содержащему лишь пробельные символы, — псевдокласса :blank [w3.org, пока не поддерживается браузерами].

Как работает :empty

Для input и textarea не так важно заполнены они или нет. Более важно заполнены ли они правильно или нет, а для этого есть псевдоклассы :valid и :invalid

  
   

Как удалить пустые блоки

Проблема 1. Блок без содержания виден из-за границ и отступов. Нужно скрыть его или пока в блоке ничего нет, показывать подсказку

  
Текст
  
Текст

Проблема 2. Пункты li в списках ol и ul имеют маркеры или нумерацию. Нужно убрать их у пустующего li

Проблема 3. Убрать из таблицы пустые ячейки или перекрасить их в неактивный цвет

 table.raz td, table.raz th  заголовок заголовок  ячейка ячейка
   заголовок заголовок  ячейка ячейка
   заголовок заголовок ячейка ячейка
   заголовок заголовок ячейка ячейка

Растянуть по высоте пустые inline-block -элементы

 div span < display: inline-block; border: 1px solid #ccc; padding: .5em; >div span:empty:before 
ПервыйВторой

Источник

Оцените статью