<input>

Никита Дубко, Яндекс Контест

<input>

Никита Дубко

<a>, Никита Дубко
<img>, Никита Дубко
document.querySelectorAll('input').forEach(input => {
  input.addEventListener('blur', () => {
    input.classList.add('touched');
  });
});
/* Показываем ошибки только для "посещённых" полей */
input.touched:invalid {
  border-color: red;
}

input.touched:valid {
  border-color: green;
}

История

HTML 2.0. Forms

INPUT TYPE

HTML 2.0. Forms
HTML 3.0. Input

INPUT TYPE

HTML 3.0. Input
HTML 4.01. The INPUT element

INPUT TYPE

HTML 4.01. The INPUT element

HTML 5. Input type

4.10.5 The input element
❌ <input name=isindex>
<input type=hidden name=_charset_>

input — уникальный

input — многогранный

MDN: input

Форма 1.
«Войти на сайт»

Принципы

input, textarea {
    font-size: inherit;
}

Почта ✉️

<input type="email">

🙃 Забавный факт

<input type="email" multiple>
/^[\w.!#$%&'*+/ =?^`{|}~-]+@[a-z\d](?:[a-z\d-]{0,61}
[a-z\d])?(?:\.[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?)*$/i;

Не мешай пользователю!

<input type="text"
       pattern=".+@.+\..+">
Stop Validating Email Addresses with Regex
<input type="text"
       pattern=".+@.+\..+"
       required>
<input type="text"
       pattern=".+@.+\..+"
       required
       inputmode="email">
Дока, inputmode
<input type="text"
       pattern=".+@.+\..+"
       required
       inputmode="email"
       enterkeyhint="next">
MDN, enterkeyhint
Дока, enterkeyhint
Дока, enterkeyhint

enterkeyhint

Дока, enterkeyhint
<label>
    Почта
    <input type="text"
           name="email"
           pattern=".+@.+\..+"
           required
           inputmode="email">
</label>
<label for="email">
    Почта
    <input type="text"
           name="email"
           id="email"
           pattern=".+@.+\..+"
           required
           inputmode="email">
</label>
Implicit labels aren't
<label for="email">Почта</label>
<input type="text"
       name="email"
       id="email"
       pattern=".+@.+\..+"
       required
       inputmode="email">
Implicit labels aren't
<input type="text"
       pattern=".+@.+\..+"
       placeholder="Почта">
→
<label for="email">Почта</label>
<input type="text"
       name="email"
       id="email"
       pattern=".+@.+\..+"
       required
       inputmode="email"
       placeholder="my@mail.com">
input::placeholder {
    color: #999;
    opacity: 1;
}

input::-webkit-input-placeholder { color: #999; }
input::-moz-placeholder { color: #999; opacity: 1; }
input:-ms-input-placeholder { color: #999; }
Плавающие лейблы

Автозаполнение ✨

Очень полезно для a11y!

Как работает автозаполнение в браузерах

Браузер пробует угадать 🔮

<input type="email">
<input type="text"
       name="email">
<input type="text"
       id="email">
<label>
    Email
    <input type="text">
</label>

Давайте поможем браузеру! 🌼

<input type="email"
       autocomplete="email">
MDN, autocomplete
<input type="email"
       autocomplete="work email">
MDN, autocomplete
Autofill DevTools
Autofill Demo

🧑‍🎨 «Фу, некрасиво!»


/* ⚠️ Использовать только в целях улучшения a11y */

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus {
    -webkit-text-fill-color: #333;
    -webkit-box-shadow: 0 0 0 1000px white inset;
    transition: background-color 5000s ease-in-out 0s;
}
<label for="email">Почта</label>
<input type="text"
       name="email"
       id="email"
       pattern=".+@.+\..+"
       required
       inputmode="email"
       placeholder="my@mail.com"
       autofocus>
Starting off right: Where autofocus shines

Валидация 🔍

⚠️ Никогда не доверяйте пользовательскому вводу!

<script>
    alert('XSS: '+document.cookie)
</script>
Progressively Enhanced Form Validation, Part 1: HTML and CSS
Progressively Enhanced Form Validation, Part 2: Layering in JavaScript
input:user-invalid {
    border: 2px solid red;
}
<label for="email">Почта</label>
<input type="text"
       id="email"
       pattern=".+@.+\..+"
       required>
form.setAttribute("novalidate", "");              // ⬅️
form.addEventListener("submit", onSubmit);

const onSubmit = (event) => {
    form
        .querySelectorAll("input")
        .forEach(updateValidationStateForInput);

    const isFormValid = form.checkValidity();     // ⬅️
    if (!isFormValid) {
        event.preventDefault();
    }
};
console.dir(input.validity);
MDN, ValidityState
const updateValidationStateForInput = (input) => {
    const isValid = input.checkValidity();

    if (input.validity.valueMissing) {
        input.setCustomValidity("Заполни, слышь!");
    }
};

❌ Недостатки

HTML Input Validation is (maybe) Good

🔨 Чиним доступность

<label for="email">Почта</label>
<input type="text"
       id="email"
       pattern=".+@.+\..+"
       required
       aria-errormessage="email-error">
<p hidden id="email-error" class="error">
    <!-- TODO: JavaScript -->
</p>
const updateValidationStateForInput = (input) => {
    const isValid = input.checkValidity();
    const errorEl = input.nextElementSibling;

    errorEl.textContent = input.validationMessage;
    errorEl.hidden = isValid;
};
Progressively Enhanced Form Validation, Part 2: Layering in JavaScript
const updateValidationStateForInput = (input) => {
    const isValid = input.checkValidity();
    const errorEl = input.nextElementSibling;

    errorEl.textContent = input.validationMessage;
    errorEl.hidden = isValid;

    if (isValid) {
        input.removeAttribute("aria-invalid");
    } else {
        input.setAttribute("aria-invalid", "true");
    }
};

✅ Ура!
Один инпут готов!

Пароль 🔑

<label for="pwd">Пароль</label>
<input type="password"
       name="pwd"
       id="pwd"
       required>
<label for="pwd">Пароль</label>
<input type="password"
       name="pwd"
       id="pwd"
       required
       autocomplete="current-password">

✅ Ура!
Второй инпут готов!

Новый пароль 🔑

<label for="new-pwd">Новый пароль</label>
<input type="password"
       name="new-pwd"
       id="new-pwd"
       required
       autocomplete="new-password">

👨🏻‍💼 Менеджеры паролей

Лучшие практики

Design your website to work best with 1Password

passwordrules

minlength: 12;
required: lower;
required: upper;
required: digit;
required: [!#$%&*@^];
Password Rules Validation Tool
<label for="new-pwd">Новый пароль</label>
<input type="password"
       name="new-pwd"
       id="new-pwd"
       required
       autocomplete="new-password"
       passwordrules="minlength: 12; required: lower;
                      required: upper; required: digit;
                      required: [!#$%&*@^];">
E@cvex9v@Qr@
CZ7h*mrE#ScJ
x&585vIz&rFK
password-manager-resources
Building multi-step login forms that work well with password managers
<input
    type="email"
    autocomplete="username"
    name="username"
    value="<user email>"
    style="display: none">

<input
    type="password"
    autocomplete="password"
    name="password"
    required>
Building multi-step login forms that work well with password managers

⏳ One Time Passcode

<input type="text"
       inputmode="numeric"
       autocomplete="one-time-code"
       maxlength="6">
Simple One-Time Passcode Inputs
navigator.credentials.get({
    otp: {
        transport: ['sms']
    }
}).then(otp => {
    input.value = otp.code;
    if (form) form.submit();
}).catch(err => {
    console.log(err);
});
SMS OTP form best practices

Чекбоксы и радио ✅

<label for="remember-me">
    <input type="checkbox"
           id="remember-me"
           name="remember-me">
    Запомнить меня
</label>

Подходы к стилизации

CSS accent-color
CSS accent-color
Fun Times Styling Checkbox States

Safari 17.4+

<input type=checkbox switch checked>
An HTML Switch Control
input-switch-polyfill

✅ Ура!
Форма готова!

11 HTML best practices for login & sign-up forms
Animated SVG Avatar v2

Форма 2.
«Профиль»

Даты 🗓️

Designing The Perfect Date And Time Picker
Designing The Perfect Date And Time Picker

😭 Особенности дейтпикеров

💁🏻‍♂️ Используйте готовые библиотеки

DatePicker
input.valueAsDate
MDN, valueAsDate

Open UI

Open UI Datepicker

😭 Штош.
1/6 готово.

Телефоны ☎️

Дока, inputmode
<label for="phone">Телефон</label>
<input type="tel"
       name="phone"
       id="phone"
       placeholder="+375291234567">
<label for="phone">Телефон</label>
<input type="text"
       name="phone"
       id="phone"
       inputmode="tel"
       autocomplete="tel-national"
       placeholder="123-555-1212">
Автодополнение номера телефона

autocomplete

MDN, autocomplete
Phone inputs and you: the designer's essential UI guide
Phone inputs and you: the designer's essential UI guide

🌍 В мире много стран

Канал Ильи Бирмана

🙏 Дайте ввести любой номер. Пожалуйста

+___(__)___-__-__
jQuery Mask Plugin
function PhoneInput() {
    const [value, setValue] = useState('');
    const ref = useRef();

    const handleChange = (e) => {
        const cursorPosition = e.target.selectionStart;
        const formatted = formatPhone(e.target.value);
        setValue(formatted);

        requestAnimationFrame(() => {
            ref.current.setSelectionRange(cursorPosition, cursorPosition);
        });
    };

    return <input ref={ref} value={value} onChange={handleChange} />;
}

😑 Ух.
2/6 готово.

Аватарка 🖼️

<input type="file"
       id="avatar"
       name="avatar"
       accept="image/*">
MDN, capture
Роман Дворнов — JSON: push the limits
<input type="file"
       id="selfie"
       name="selfie"
       accept="image/*"
       capture="user">
MDN, capture
Чиним img - Дмитрий Махнёв
<input type="file"
       id="photos"
       webkitdirectory
       directory
       multiple>
How to Add Folder Upload to Your Web Application
folderInput.addEventListener('change', function(e) {
    const files = e.target.files;
    const fileArray = Array.from(files);

    fileArray.forEach(file => {
        const relativePath = file.webkitRelativePath
                          || file.name;
        // Some logging
    });

    uploadFolder(fileArray);
});
How to Add Folder Upload to Your Web Application

😨 Ух.
3/6 готово.

Числа 💯

input[type="number"] {
    appearance: textfield;
}
A complete guide to the HTML number input
const numberInputs = document.querySelectorAll('.stepper');
numberInputs.forEach((input) => {
    input.addEventListener("command", (event) => {
        if (event.command === "--increment") {
            input.stepUp();
        } else if (event.command === "--decrement") {
            input.stepDown();
        }
    });
});
A complete guide to the HTML number input
input.valueAsNumber
MDN, valueAsNumber

3.14 vs 3,14

const input = document.querySelector('input[type="number"]');

input.addEventListener('blur', (e) => {
    e.target.value = e.target.value.replace(',', '.');
});

😀 Уф.
4/6 готово.

autocapitalize=words
MDN, autocapitalize
spellcheck=false
MDN, spellcheck

Елизавета Варвара —
валидное имя

Ю —
валидная фамилия

Адовый UX
Адовый UX

✅ Ура!
6/6 готово.

Говорил же тебе, что там не на 5 минут делов

Бонусы 🎁

<!-- ⚠️ будет отправлено на сервер -->
<input type="text" readonly>
Avoid Read-only Controls
<!-- ❌ ломает UX и a11y -->
<input type="text" disabled>
Don’t Disable Form Controls
<div class="input input_readonly">
    Текст
</div>
Use Cases for Field Sizing
<input type="search">
Этот безумный, безумный, безумный, безумный search bar – Роман Прудников
CSS Basic User Interface Module Level 4
caret-animation: manual;
caret-shape: underscore;

Капча 🤖

<input id="captcha"
       type="image"
       name="captcha"
       width="100"
       height="30"
       alt="А не робот ли ты часом?"
       src="path/to/captcha.png">
                                                ↓
{ captcha: { x: 10, y: 20 } }
MDN, type image
<a href="/imagemapper">
    <img src="image.png" ismap />
</a>
<form action="/login" method="get">
    <label for="username">Username</label>
    <input type="text"
           name="username"
           id="username"
           required>
</form>

<input type="submit" value="Потеряшка">
The Form Attribute - Enhancing Form Layout Flexibility
<form action="/login" method="get" id="my-form">
    <label for="username">Username</label>
    <input type="text"
           name="username"
           id="username"
           required>
</form>

<input type="submit" form="my-form" value="Потеряшка">
The Form Attribute - Enhancing Form Layout Flexibility

input
+
label
+
селекторы
=
💪 могущество

Игры на CSS. Часть 2: StarCraft

Резюмируем 📚

Пошаговый алгоритм

🤖 AI-агенты лучше работают с семантичной вёрсткой

SKILL.md

How to Build forms Agent Skill

Берегите природу!

mefody.dev/talks/input/
t.me/mefody_dev QR-код на голосование