Никита Дубко, Яндекс Контест
<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
TEXTPASSWORDCHECKBOXRADIOIMAGEHIDDENSUBMITRESET
HTML 3.0. Input
textpasswordcheckboxradiohiddensubmitimagereset+ range+ scribble+ file
HTML 4.01. The INPUT element
TEXTPASSWORDCHECKBOXRADIOHIDDENSUBMITIMAGERESETFILE+ BUTTON- range- scribblehiddentextpasswordcheckboxradiosubmitimageresetfilebutton+ search+ tel+ url+ email+ date+ month+ week+ time- datetime+ datetime-local+ number+ range (😁)+ color
❌ <input name=isindex>
<input type=hidden name=_charset_>
MDN: input
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">
<input type="text"
pattern=".+@.+\..+"
required
inputmode="email"
enterkeyhint="next">
MDN, enterkeyhint
enterdonegonextprevioussearchsend
<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; }
Плавающие лейблы
Как работает автозаполнение в браузерах
<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("Заполни, слышь!");
}
};
<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">
id и name для каждого поля.input находятся внутри form.method у форм.autocomplete у элементов.passwordrulesminlength: 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
<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>
accent-color;input;label.
CSS accent-color
<input type=checkbox switch checked>
An HTML Switch Control
input-switch-polyfill
11 HTML best practices for login & sign-up forms
Designing The Perfect Date And Time Picker
Designing The Perfect Date And Time Picker
MM/DD/YYYY vs DD.MM.YYYY.Date.
DatePicker
input.valueAsDate
MDN, valueAsDate
Дока, 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">
Автодополнение номера телефона
teltel-country-codetel-nationaltel-area-codetel-localtel-extension
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} />;
}
<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
input[type="number"] {
appearance: textfield;
}
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
const input = document.querySelector('input[type="number"]');
input.addEventListener('blur', (e) => {
e.target.value = e.target.value.replace(',', '.');
});
autocapitalize=words
MDN, autocapitalize
spellcheck=false
MDN, spellcheck
Адовый UX
Адовый UX
Говорил же тебе, что там не на 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 – Роман Прудников
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
inputlabel
Игры на CSS. Часть 2: StarCraft