Css valid and invalid

:invalid , :valid

Валидируем форму прямо в браузере. Без JavaScript, регистрации и смс.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Псевдоклассы используются для стилизации полей формы, филдсетов, либо самой формы:

Пример

Скопировать ссылку «Пример» Скопировано

          Я согласен с политикой обработки персональных данных       form> div class="form-row"> label for="first-name">Имя:label> input type="text" name="first-name" id="first-name" required> span class="validity-icon">span> div> div class="form-row"> label for="email">E-mail:label> input type="email" name="email" id="email"> span class="validity-icon">span> div> div class="form-row"> label> input type="checkbox" name="agree" id="agree" required> Я согласен с политикой обработки персональных данных label> div> div class="form-row"> button type="submit">Отправитьbutton> div> form>      
 input:invalid  border: 2px solid red;> input:invalid + .validity-icon::before  content: '✖'; color: red;> input:valid + .validity-icon::before  content: '✓'; color: green;> [type="checkbox"]:invalid  outline: 2px solid red; outline-offset: 2px;> input:invalid  border: 2px solid red; > input:invalid + .validity-icon::before  content: '✖'; color: red; > input:valid + .validity-icon::before  content: '✓'; color: green; > [type="checkbox"]:invalid  outline: 2px solid red; outline-offset: 2px; >      

Как понять

Скопировать ссылку «Как понять» Скопировано

Часто на сайтах мы встречаем формы. Это могут быть формы регистрации или формы оплаты покупки в интернет-магазине. Некоторые поля ввода и другие элементы управления в этих формах могут иметь особые требования к заполнению. Например, какие-то поля ввода должны быть обязательно заполнены, какие-то — иметь определённый формат данных (к примеру, текст в поле с типом email должен содержать знак @ ).

Чтобы показать что поле ввода заполнено корректно к нему можно применить особые стили используя псевдокласс :valid . Аналогично, для некорректно заполненного поля мы можем применить особые стили используя псевдокласс :invalid .

В примере выше можно увидеть пару моментов:

  • Поле ввода имени и чекбокс обязательны к заполнению, но не заполнены, поэтому псевдокласс :invalid применяется к ним сразу же.
  • Поле ввода электронной почты необязательно к заполнению, поэтому к нему сразу же применён псевдокласс :valid .

Но если ввести в поле хотя бы один символ, браузер запускает проверку на корректность ввода email (из-за того, что мы указали type = «email» ) и применяет псевдокласс :invalid до тех пор, пока не будет введён корректный адрес электронной почты.

Также указанные псевдоклассы применяются и к самой форме, в которой находится инпут.

В примере выше можно увидеть, что при наличии филдсета к нему также будет применён соответствующий псевдокласс.

 form:invalid  border-color: red;> form:valid  border-color: green;> fieldset:invalid  border-color: red;> fieldset:valid  border-color: green;> form:invalid  border-color: red; > form:valid  border-color: green; > fieldset:invalid  border-color: red; > fieldset:valid  border-color: green; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

К любому селектору добавляем двоеточие и ключевое слово invalid или valid . Селектор должен указывать на интерактивный элемент ввода, у которого предусмотрены правила проверки, на форму или на филдсет. Например, абзац браузер не умеет проверять на правильность, а значит, селектор p : invalid будет бесполезен.

Например, так выглядит селектор по классу:

 .element:invalid  color: red;> .element:valid  color: green;> .element:invalid  color: red; > .element:valid  color: green; >      

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Если в форме есть группа связанных радиокнопок ( ), то если хотя бы у одной есть атрибут required , псевдокласс :invalid будет применён ко всем радиокнопкам сразу.

💡 Псевдоклассы :invalid или :valid применяются и к самой форме, и к тегу , в зависимости от того, есть ли внутри ошибки, или все инпуты заполнены верно.

💡 В отличие от комплексной валидации формы, которая происходит при попытке её отправить, эти псевдоклассы работают в реальном времени и сохраняют свою актуальность даже во время ввода.

На практике

Скопировать ссылку «На практике» Скопировано

Денис Ежков советует

Скопировать ссылку «Денис Ежков советует» Скопировано

🛠 В настоящий момент стили для псевдокласса :invalid применяются к невалидному полю сразу же, что не всегда удобно. Было бы круто, если бы валидация включалась, только если пользователь начал что-то вводить, но, к сожалению, пока нет такой возможности «из коробки».

В будущих версиях спецификации CSS должен появиться псевдокласс :user — invalid , который задуман как раз для целей, описанных выше. То есть он будет применяться, например, к полю ввода только после того, как пользователь начал там что-то писать.

Но это пока перспективы, а что же можно сделать сейчас? В настоящий момент добиться похожего поведения можно только для полей ввода. При этом нужно выполнить два условия:

      type="text" name="first-name" placeholder="Например, Пётр" required>     type="email" name="email" placeholder="Например, mymail@gmail.com" >      form> div class="form-row"> label for="first-name">Имя:label> input type="text" name="first-name" id="first-name" placeholder="Например, Пётр" required> span class="validity-icon">span> div> div class="form-row"> label for="email">E-mail:label> input type="email" name="email" id="email" placeholder="Например, mymail@gmail.com" > span class="validity-icon">span> div> div class="form-row"> button type="submit">Отправитьbutton> div> form>      
 input:invalid  border: 2px solid red;> input:invalid:placeholder-shown  border-color: black;> input:invalid:placeholder-shown + .validity-icon::before,input:valid:placeholder-shown + .validity-icon::before  visibility: hidden;> input:invalid  border: 2px solid red; > input:invalid:placeholder-shown  border-color: black; > input:invalid:placeholder-shown + .validity-icon::before, input:valid:placeholder-shown + .validity-icon::before  visibility: hidden; >      

Источник

:valid and :invalid pseudo-classes

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">Textlabel>
input type="text" required id="text" name="text">

label for="email">Emaillabel>
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">Whateverlabel>
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

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.

Источник

Читайте также:  Static code in java class
Оцените статью