Css ошибки input

Internet Explorer Chrome Opera Safari Firefox Android iOS
8.0+ 9.5+ 5.0+ 4.0+ 2.1+ 3.0+

Краткая информация

Применяется К <input>
Ссылка на спецификацию http://www.w3.org/TR/css3-ui/#pseudo-validity

Версии CSS

CSS 1 CSS 2 CSS 2.1 CSS 3

Описание

Применяется к полям формы, содержимое которых не соответствует указанному типу. Например, для type=«number» должно вводиться число, а не буквы, для type=«email» корректный адрес электронной почты.

Синтаксис

input:invalid { … }

Значения

Нет.

Пример

HTML5CSS3IECrOpSaFx

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>:invalid</title>
  <style>
   input:invalid {
    background: #fdd; /* Красный цвет фона */
   }
   input:valid {
    background: #dfd; /* Зеленый цвет фона */
   }
  </style>
 </head>
 <body>
  <form>
   <p>Адрес сайта</p>
   <p><input type="url" required></p>
   <p>Адрес электронной почты</p>
   <p><input type="email" required></p>
   <p><input type="submit" value="Отправить" /></p>
  </form>
 </body>
</html>

В данном примере корректно заполненные поля формы обозначаются зеленым фоном, а некорректные красным. Результат примера в Chrome показан на рис. 1.

Использование псевдокласса :invalid

Рис. 1. Использование псевдокласса :invalid

This tutorial will show you how to create and customize error messaging for various form elements. In this tutorial, we will customize everything from a basic error message to input field errors and tooltips. The best part? We will be using only CSS for customizations – that means no images or javascript required!

HTML

Below is the markup for the form elements we will be creating error messaging for. This is all of the HTML used throughout this tutorial. Copy and paste this code into your working file:

<!-- Basic Error Message -->
<div class="error-message">
  <span class="error-text">Checkout could not be completed. Please check your login information and try again.</span>
</div>
 
<!-- Input Field Error -->
<div class="input-group error">
  <label>Password *</label> 
  <input type="text">
  <div class="error-message">Password is a required field.</div>
</div>
 
<!-- Input Field Error with Tooltip -->
<div class="input-group error">
  <label>Quantity</label> 
  <input type="text">
  <div class="error-tip">Enter a quantity</div>
</div>

CSS

Now onto my personal favorite: the CSS. We will keep the basic functionality of the form elements but completely customize their appearance. In the end, they will stand on their own as custom design elements that thoughtfully guide the user through the form process, making it as straightforward and painless as possible.

Basic Error Message

Let’s start with a basic error message. We are going to customize the HTML above to look like this:

This is what we start out with, by default, after adding the HTML:

basic error message default

Customizing a basic error message is really simple. All we have to do is give our text a colored background and a couple font styles using CSS. To style the error message background, add the following styles to your CSS stylesheet:

.error-message {
  background-color: #fce4e4;
  border: 1px solid #fcc2c3;
  float: left;
  padding: 20px 30px;
}

Now let’s style the text itself by adding the following font styles:

.error-text {
  color: #cc0033;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 13px;
  font-weight: bold;
  line-height: 20px;
  text-shadow: 1px 1px rgba(250,250,250,.3);
}

That’s it! Keep reading to learn how to style input field and tooltip errors.

Input Field Error

Now that we have our basic error message styled, let’s work on input field errors. This is what the final product will look like:

error field input

And this is what we start out with by default:

error field input default

First, we want to override the browser’s default styles. Add the following CSS to give your input field a custom look:

/* Basic Input Styling */
.input-group {
  color: #333;
  float: left;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 13px;
  line-height: 20px;
  margin: 0 20px 10px;
  width: 200px;
}

label {
  display: block;
  margin-bottom: 2px;
}

input[type=text] {
  background: #fff;
  border: 1px solid #999;
  float: left;
  font-size: 13px;
  height: 33px;
  margin: 0;
  padding: 0 0 0 15px;
  width: 100%;
}

Next, we need to add the styling for the error message that displays when a user does not correctly fill out an input field (i.e. the “This is a required field” message):

.error-message {
  color: #cc0033;
  display: inline-block;
  font-size: 12px;
  line-height: 15px;
  margin: 5px 0 0;
}

Lastly, add the error-specific styling for the input field elements:

.error label {
  color: #cc0033;
}

.error input[type=text] {
  background-color: #fce4e4;
  border: 1px solid #cc0033;
  outline: none;
}

Input Field Error with Tooltip

The last element we’re tackling is the tooltip. It is slightly more complicated than the others but well worth the effort. We will also be utilizing Sass nesting to better organize our code, and because we are only using SCSS it is 100% editable and scalable.

Once we are done, the tooltip will look like this:

error field input tooltip

And by default, this is what we start with after adding the HTML:

error field input tooltip default

First, we override the browser’s default styles with our own custom styling:

/* Basic Input Styling */
.input-group {
  color: #333;
  float: left;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 13px;
  line-height: 20px;
  margin-bottom: 10px;
  width: 100%;
}

label {
  display: block;
  margin-bottom: 5px;
}

input[type=text] {
  background: #fff;
  border: 1px solid #ccc;
  color: #333;
  float: left;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 13px;
  height: 33px;
  line-height: 20px;
  margin: 0;
  padding: 0 0 0 15px;
  width: 45px;
}

Just like our previous example, we need to add the tooltip error message styling that displays when a form error occurs. Note: we are using Sass here to nest the tooltip’s left arrow properties. This comes in handy when trying to keep track of which values are assigned to the tooltip specifically:

/* Tooltip Styling */
.error-tip {
  background-color: #fce4e4;
  border: 1px solid #fcc2c3;
  border-radius: 7px;
  -moz-border-radius: 7px;
  -webkit-border-radius: 7px;
  display: inline;
  color: #cc0033;
  float: left;
  font-weight: bold;
  line-height: 24px;
  position: relative;
  padding: 7px 11px 4px;
  margin-left: 17px;
  // Left Arrow Styling Starts Here
  &:after, &:before {
    content: '';
    border: 7px solid transparent;
    position: absolute;
    top: 11px;
  }
  &:after {
    border-right: 7px solid #fce4e4;
    left: -14px;
  }
  &:before {
    border-right: 7px solid #fcc2c3;
    left: -15px;
  }
} // end .error-tip

Now all that’s left to do is define the input’s error-specific styling. Again, we will nest these styles under an “error” class selector to make classification and future changes easier:

/* Error Styling */
.error.input-group {
  label {
    color: #cc0033;
    font-weight: bold;
  }
  input {
    border: 2px solid #cc0033;
    line-height: 37px;
    outline: none;
  }
  .status {
    display: none;
  }
  .error-tip {
    display: inline;
  }
} // end .error

And that’s it! All the code you need to customize error messaging for default form elements. To experiment with the final results and copy and paste to your heart’s content (without fear of breaking anything), jump on over to Codepen by selecting any of the tutorial links below.

Codepen/Tutorial Links

All:  codepen.io/seskew/
Basic Error Message:  codepen.io/seskew/pen/akhLx
Input Field Error:  codepen.io/seskew/pen/XKJKNQ
Input Field Error with Tooltip:  codepen.io/seskew/pen/NrPNBp

Ни для кого не секрет, что онлайн-формы могут стать серьёзным испытанием для пользователей. Особенно когда они выглядят как список полей для ввода без каких-либо подсказок. Однако мы, как разработчики, можем значительно облегчить жизнь посетителям наших сайтов.

Используем CSS

В CSS существует четыре специальных псевдокласса, применимых к полям формы: :valid (валидное поле), :invalid (невалидное), :required (обязательное) и :optional (необязательное). Их можно использовать, чтобы добавлять некоторые — хотя и весьма ограниченные — подсказки пользователям, заполняющим форму.

Используя :valid и :invalid, мы можем показать пользователю, правильно ли заполнено поле по мере ввода.

input:valid {
  border-color: green;
}

input:invalid {
  border-color: red;
}

Стилизация псевдоклассов :valid и :invalid

Стилизация псевдоклассов : valid и : invalid

Однако с этим способом связана одна проблема: стили применяются до того, как пользователь начнёт работу с формой. Поля, обязательные для заполнения, сразу подсветятся нам как :invalid, а необязательные — как :valid. Это значит, что пользователь, даже не приступив к заполнению формы, может сразу же получить негативную обратную связь. Не очень-то хорошо.

Стилизация состояний :required и :optional сама по себе не особо полезна, поскольку эта информация обычно указывается в подписях к полям формы. Однако мы можем объединить эти состояния с псевдоклассами :valid / :invalid и стилизовать их комбинации. Например, мы хотим показывать лишь положительный результат, когда валидно обязательное к заполнению поле.

input:required:valid {
  border-color: green;
}

Стилизация по :valid и :required

Стилизация по : valid и : required

Используем JavaScript

JavaScript даёт намного больше возможностей для улучшения работы пользователей с формами. Давайте рассмотрим в качестве примера три числовых поля, у каждого из которых установлен минимум в 10, максимум в 100 и шаг в 10 единиц.

<form>
  <label>
    Number Input 1
   <input type="number" min="10" max="100" step="10">
  </label>

  <label>
    Number Input 2
   <input type="number" min="10" max="100" step="10">
  </label>

  <label>
    Number Input 3
   <input type="number" min="10" max="100" step="10">
  </label>

  <input type="submit">
</form>

Устанавливая атрибуты minmax и step, мы можем быть уверены в правильности значения только тогда, когда пользователь использует специальные контролы числового поля. Но что мешает пользователю ввести вручную некорректные данные? Вот что произойдёт, если он вставит 112 и 123 в три поля и отправит форму:

Стандартный тултип валидации

Стандартный тултип валидации

В результате всё, что получит пользователь — это сообщение об ошибке для первого поля. Кроме того, в этом сообщении будет указано лишь одно несоответствие из двух требуемых. Такое поведение можно исправить, изменяя показываемые валидатором сообщения.

Добавляем несколько сообщений об ошибках в один тултип

Валидируя поля, браузер проверяет их по определённому списку потенциальных ошибок. В каждом поле содержится специальный объект validity, включающий в себя список булевых значений, характеризующих ту или иную проверку на валидность. Например, вот такой validity-объект будет у поля, когда пользователь введёт в него 1:

input.validity = {
  valid: false // Поле валидно
  customError: false // Установленно специальное сообщение ошибки
  patternMismatch: false // Значение не удовлетворяет шаблону, установленному в атрибуте pattern
  rangeOverflow: false // Значение превосходит атрибут max
  rangeUnderflow: true // Значение меньше атрибута min
  stepMismatch: true // Значение не соответствует указаному шагу
  tooLong: false // Значение слишком длинное
  tooShort: false // Значение слишком короткое
  typeMismatch: false // Значение не соответствует указаному атрибуту type
  valueMissing: false // Отсутствует обязательное значение
};

Примечание переводчика: Слово «mismatch» переводится как «несоответствие». Поэтому в значениях patternMismatchstepMismatch и typeMismatch обратная логика: true — значение не удовлетворяет атрибуту, false — удовлетворяет.

По умолчанию браузер отобразит лишь одну ошибку. Что мы можем сделать, так это проверить все эти значения самостоятельно и, если найдутся ошибки, сохранить их. Как только мы сохраним все ошибки для одного поля, мы можем отобразить весь их список в виде специального сообщения об ошибке при помощи функции setCustomValidity().

function CustomValidation() { }

CustomValidation.prototype = {
  // Установим пустой массив сообщений об ошибках
  invalidities: [],

  // Метод, проверяющий валидность
  checkValidity: function(input) {

    var validity = input.validity;

    if (validity.patternMismatch) {
      this.addInvalidity('This is the wrong pattern for this field');
    }

    if (validity.rangeOverflow) {
      var max = getAttributeValue(input, 'max');
      this.addInvalidity('The maximum value should be ' + max);
    }

    if (validity.rangeUnderflow) {
      var min = getAttributeValue(input, 'min');
      this.addInvalidity('The minimum value should be ' + min);
    }

    if (validity.stepMismatch) {
      var step = getAttributeValue(input, 'step');
      this.addInvalidity('This number needs to be a multiple of ' + step);
    }

    // И остальные проверки валидности...
  },

  // Добавляем сообщение об ошибке в массив ошибок
  addInvalidity: function(message) {
    this.invalidities.push(message);
  },

  // Получаем общий текст сообщений об ошибках
  getInvalidities: function() {
    return this.invalidities.join('. n');
  }
};

// Добавляем обработчик клика на кнопку отправки формы
submit.addEventListener('click', function(e) {
  // Пройдёмся по всем полям
  for (var i = 0; i < inputs.length; i++) {

    var input = inputs[i];

    // Проверим валидность поля, используя встроенную в JavaScript функцию checkValidity()
    if (input.checkValidity() == false) {

      var inputCustomValidation = new CustomValidation(); // Создадим объект CustomValidation
      inputCustomValidation.checkValidity(input); // Выявим ошибки
      var customValidityMessage = inputCustomValidation.getInvalidities(); // Получим все сообщения об ошибках
      input.setCustomValidity(customValidityMessage); // Установим специальное сообщение об ошибке

    } // закончился if
  } // закончился цикл
});

Теперь при попытке отправить форму мы увидим вот это:

Отображаем несколько ошибок в одном тултипе

Стало лучше, поскольку теперь будут показываться все сообщения об ошибках, связанные с конкретным полем. Однако другая проблема всё ещё не решена: ошибки по-прежнему показываются лишь для первого поля.

Это ограничение валидации, устанавливаемое браузером. Чтобы его побороть, нам нужно пойти другим путём.

Показываем все ошибки для всех полей

Вместо того, чтобы использовать встроенный тултип, мы можем добавлять сообщения об ошибках напрямую в DOM. Таким образом, все ошибки будут выводиться рядом с соответствующим полем.

Этого можно добиться какой-то парой дополнительных строчек в нашем коде:

CustomValidation.prototype.getInvaliditiesForHTML = function() {
  return this.invalidities.join('. <br>');
}

// Добавляем обработчик клика на кнопку отправки формы
submit.addEventListener('click', function(e) {
  // Пройдёмся по всем полям
  for (var i = 0; i < inputs.length; i++) {

    var input = inputs[i];

    // Проверим валидность поля, используя встроенную в JavaScript функцию checkValidity()
    if (input.checkValidity() == false) {

      var inputCustomValidation = new CustomValidation(); // Создадим объект CustomValidation
      inputCustomValidation.checkValidity(input); // Выявим ошибки
      var customValidityMessage = inputCustomValidation.getInvalidities(); // Получим все сообщения об ошибках
      input.setCustomValidity(customValidityMessage); // Установим специальное сообщение об ошибке

      // Добавим ошибки в документ
      var customValidityMessageForHTML = inputCustomValidation.getInvaliditiesForHTML();
      input.insertAdjacentHTML('afterend', '<p class="error-message">' + customValidityMessageForHTML + '</p>')
      stopSubmit = true;

    } // закончился if
  } // закончился цикл

  if (stopSubmit) {
    e.preventDefault();
  }
});

Вот что происходит при клике на submit теперь:

Отображаем все ошибки для всех полей в DOM

Отображаем все ошибки для всех полей в DOM

Используем нестандартные проверки валидности

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

Так как мы уже проверяем все возможные ошибки вручную в нашей функции CustomValidation.prototype.checkValidity, мы можем просто-напросто добавить туда ещё несколько проверок.

CustomValidation.prototype.checkValidity = function(input) {

  // Тут идут встроенные проверки валидности

  // А тут специальные
  if (!input.value.match(/[a-z]/g)) {
    this.addInvalidity('At least 1 lowercase letter is required');
  }

  if (!input.value.match(/[A-Z]/g)) {
    this.addInvalidity('At least 1 uppercase letter is required');
  }
};

Валидация в реальном времени

Хотя текущий способ выглядит намного лучше, он тоже не без изъянов. Наихудший из недочётов заключается в том, что пользователь не сможет увидеть никаких сообщений, пока не нажмёт на кнопку отправки формы. Было бы гораздо лучше, если бы валидация поля происходила сразу же при его заполнении. Можно выделить три правила для того, чтобы с формой было удобно работать:

  1. Требования для каждого поля чётко видны до того, как пользователь начал печатать.
  2. Как только пользователь начинает вводить данные, соблюдая требования, он сразу видит индикатор успешного заполнения поля или подсказки, если есть ошибки.
  3. Нужно отображать сообщения об ошибках таким образом, чтобы пользователь не мог отправить некорректно заполненную форму.

Пример валидации в реально времени

Пример валидации в реально времени

Если вы хотите попробовать свои силы (и даже сделать получше), вы можете воспользоваться вот этим шаблоном.


«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

ТелеграмПодкастБесплатные учебники

:invalid

Try it

Этот псевдо-класс полезен для подсветки ошибок поля для пользователя.

Syntax

Examples

Раскрашивание элементов для отображения проверки

HTML

<form>
  <div class="field">
    <label for="url_input">Enter a URL:</label>
    <input type="url" id="url_input">
  </div>

  <div class="field">
    <label for="email_input">Enter an email address:</label>
    <input type="email" id="email_input" required>
  </div>
</form>

CSS

label {
  display: block;
  margin: 1px;
  padding: 1px;
}

.field {
  margin: 1px;
  padding: 1px;
}

input:invalid {
  background-color: #ffdddd;
}

form:invalid {
  border: 5px solid #ffdddd;
}

input:valid {
  background-color: #ddffdd;
}

form:valid {
  border: 5px solid #ddffdd;
}

input:required {
  border-color: #800000;
  border-width: 3px;
}

input:required:invalid {
  border-color: #c00000;
}

Result

Поэтапное отображение разделов

В этом примере мы используем :invalid вместе с ~ , общим комбинатором родственных элементов, чтобы форма появлялась поэтапно, поэтому форма изначально показывает первый элемент, который нужно заполнить, и когда пользователь завершает каждый элемент, форма отображает следующий. Когда вся форма заполнена, пользователь может отправить ее.

HTML

<form>

  <fieldset>
    <label for="form-name">Name</label><br>
    <input type="text" name="name" id="form-name" required>
  </fieldset>

  <fieldset>
    <label for="form-email">Email Address</label><br>
    <input type="email" name="email" id="form-email" required>
  </fieldset>

  <fieldset>
    <label for="form-message">Message</label><br>
    <textarea name="message" id="form-message" required></textarea>
  </fieldset>

  <button type="submit" name="send">Submit</button>

</form>

CSS

fieldset:invalid~fieldset {
  display: none;
}


form:invalid button {
  opacity: 0.3;
  pointer-events: none;
}

input, textarea {
  box-sizing: border-box;
  width: 100%;
  font-family:monospace;
  padding: 0.25em 0.5em;
}

button {
  width: 100%;
  border: thin solid darkgrey;
  font-size: 1.25em;
  background-color: darkgrey;
  color: white;
}

Result

Accessibility concerns

Notes

Radio buttons

Если какой — либо один из переключателей в группе required , то :invalid псевдо-класс применяется ко всем из них , если не выбран ни один из кнопок в группе. (Сгруппированные переключатели имеют одинаковое значение для своего атрибута name .)

Gecko defaults

По умолчанию Gecko не применяет стиль к псевдоклассу :invalid . Однако он применяет стиль (красное «свечение» с использованием свойства box-shadow ) к псевдоклассу :user-invalid , который применяется в подмножестве случаев для :invalid .

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox для Android Opera Android Safari на IOS Samsung Internet
:invalid

10

12

4

10

10

5

37

18

4

10.1

5

1.0

form

40

79

13

No

27

9

40

40

14

27

9

4.0

See also

  • Другие проверки , связанные с псевдо-классы: :required , :optional , :valid
  • Связанный Mozilla псевдо-классы: :user-invalid , :-moz-submit-invalid
  • Проверка данных формы
  • Доступ к состоянию действительности из JavaScript


CSS

  • :in-range

    CSS-псевдокласс :in-range представляет элемент <input>, текущее значение которого находится в пределах, заданных атрибутами min и max.

  • :indeterminate

    Псевдокласс CSS :indeterminate представляет любой элемент формы,состояние которого является таким:флажки,у которых атрибут HTML установлен в true,радиокнопки

  • : is () (: соответствует (),: any ())

    Примечание::matches()был переименован в :is()в выпуске CSSWG #3258.

  • :lang()

    Псевдокласс CSS :lang()сопоставляет элементы на основе языка,которым они определены Примечание:В HTML язык определяется комбинацией атрибутов,

20 October 2020

It is 2020 all modern browser support native form validation, and they also support styling valid and invalid form elements via CSS. In this article you will learn how to use the :valid and :invalid pseudo classes, when to use them and why it depends.

What are the :valid and :invalid pseudo classes #

By default, every form element is valid and therefore also the :valid pseudo-class will be executed. We can change that however by defining attributes. The following attributes are available today (2020) to get build-in validation: required, minlength, maxlength, min, max, type and pattern.

Here are two examples where :invalid would be applied:

<label for="text">Text</label>
<input type="text" required id="text" name="text">

<label for="email">Email</label>
<input type="email" value="a" id="email" name="email">

The first one because it is required and is empty, the second one because it has type="email" and the current value »a« is not an email address.

So, this way you can style form elements differently, based on if they are valid or not.

One thing to note here about minlength — in this case validation only happens after user input, so if you have the following in your HTML,

<label for="whatever">Whatever</label>
<input type="text" minlength="12" value="123" id="whatever" name="whatever">

the :valid selector will be applied. However, once the user enters the same value »123« or any other value with a minimum length below twelve the :invalid selector will be applied.

Blame the user #

The big issue with setting :invalid on page load is that we blame the user by saying »Look, there is an error — correct that«, although the user had no chance to not make the »error« as they haven’t even done anything.

The same is true for :valid, we tell the user »Look, this is already valid« and the user may rightly ask »Why is this form element even there if it doesn’t require any input from my side«

Let’s have a look at some ways to change the default behaviour and try to not confuse users.

Restrict with CSS #

To not show the valid/invalid states without user interaction we can use CSS. In general there are two ways of doing this.

:focus #

The first approach is to only trigger :valid/:invalid when a form element has focus.

input:focus:invalid {
border: 2px solid red;
}

This way the user first have to interact with the page to get a different styling. This comes with other issues though, as once the user moves to another form element the previous one will lose the validation styling.

:placeholder-shown #

The other approach is to use the :placeholder-shown pseudo class.

input:not(:placeholder-shown):invalid {
border: 2px solid red;
}

This way, elements only get marked as invalid when the placeholder is not shown. We can enhance this further by only using :invalid when the form element is not focused.

input:not(:placeholder-shown):not(:focus):invalid {
border: 2px solid red;
}

When you hear placeholder, you may think »placeholders are bad for accessibility and shouldn’t be used« and this is true to some point, as you should never replace a real label element with a placeholder text and should avoid placeholder text in most cases, but we don’t need any text for placeholder to get this working, all we need is

placeholder=" "

That said, in some cases this may still be confusing for users, but it is probably the best approach we have.

Restrict with JavaScript #

Okay, so we can now switch to JavaScript to correct that to our needs and make it perfect for everybody. I long thought about the best way to do this and I always ended up with the conclusion that it is not worth it as every solution I can think of would still not be perfect and might do more harm than good in the end. That said, there might be a way to do this, and if you found such a solution please let me know.

:user-invalid #

To help with all the issues described here, there is a new proposed pseudo-class called :user-invalid. It is still in early stage, but it looks promising to solve the issues many have with :invalid. For example, a user agent (browser) may choose to have :user-invalid match an :invalid element once the user has typed some text into it and changed the focus to another element, and to stop matching only after the user has successfully corrected the input.

It is currently not supported in any browser, but Firefox has support for the non-standard pseudo-class :-moz-ui-invalid.

Not use colours alone #

One thing you should always keep in mind is, that you should not indicate valid/invalid states with colour alone. Red–green colour blindness affects a lot of people for example, and for them there is no/little difference between a green and a red border.

As form elements are replaced elements, we can’t use pseudo elements (::before/::after) directly on them as of now, so as a workaround we can use an empty span next to form elements to show an icon for example.

<input type="text" required>
<span></span>
input:valid + span::after {
content: "";
background: transparent url(valid.svg) no-repeat 0 0;
}

input:invalid + span::after {
content: "";
background: transparent url(invalid.svg) no-repeat 0 0;
}

Browser support #

Support for :valid and :invalid is very good, and even works all the way back to Internet Explorer 10. However, if you want to use :valid or :invalid on the form element, note that it is not supported in Internet Explorer.

In general, you can safely use these pseudo-classes to enhance your forms without needing to add a polyfill for unsupported browsers.

Conclusion #

It depends, and it is complicated. As outlined in this article you should always carefully test your chosen approach with real users. It might be even better to not use :valid/:invalid as it might to more harm than good.

Resources #

MDN :valid

MDN :invalid

MDN: :placeholder-shown

MDN: Client-side form validation

Browser support for CSS selector :valid

Browser support for CSS selector :invalid

How to target non-empty but invalid input elements with CSS

Updates #

  • 10.11.2020 — Added info about :user-invalid

Понравилась статья? Поделить с друзьями:
  • Ccm b150c87 ошибка на вольво
  • Css ошибка синтаксического анализа
  • Ccleaner произошла ошибка 91613
  • Css анимация ошибки
  • Civilization 5 ошибка при подключении к локальной сети