input type url для чего

Новые типы элемента

В HTML5 из этого поведения извлекается польза. А именно, в элемент было добавлено несколько новых типов, и если какой-либо браузер не поддерживает их, он будет обрабатывать их как обычные текстовые поля. Например, для ввода адреса электронной почты можно создать поле нового типа email:

Если просматривать страницу с этим кодом в браузере, который не поддерживает тип email для элемента (например, Internet Explorer), то это поле отобразится как обычное текстовое поле. Но браузеры, поддерживающие формы HTML5 немного умнее могут делать следующее:

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

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

Выполнять проверку. Браузеры могут выполнять более сложные проверки после того, как пользователь нажмет кнопку для отправки данных.

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

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

К сожалению, не все современные браузеры удовлетворяют этим требованиям. Некоторые распознают новые типы данных и предоставляют кое-какие возможности редактирования, но не проверки. Многие браузеры понимают один тип данных, но не другой. Особенно проблемные в этом отношении мобильные браузеры — они предоставляют некоторые удобства редактирования, но никаких возможностей проверки.

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

Поддержка новых типов данных основными браузерами

Тип данных IE Firefox Chrome Safari Opera Safari iOS Android
email 4 10 5 10.6
url 4 10 5 10.6
search (без проверки)
tel (без проверки)
number 10 5
range 6 5 11
datetime, date, month, week, time 10 11
color 11

Хотя мобильные браузеры Safari для iOS и Android не поддерживают проверку, предоставление этими браузерами специализированных клавиатур является значительным удобством, поэтому в приложениях для этих веб-обозревателей стоит использовать специальные типы данных.

Адреса электронной почты

Тип данных email используется для полей, предназначенных для ввода адресов электронной почты. В общем, адрес электронной почты состоит из строки символов (использование некоторых символов не допускается). Допустимый адрес должен содержать символ @ и точку, между которыми должен быть минимум один символ, а после точки — минимум два символа:

Тип email поддерживает атрибут multiple, который позволяет вводить несколько адресов в поле. Но эти несколько адресов все равно выглядят, как одна строка текста, только разделены запятыми.

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

URL-адреса

Тип url применяется для полей ввода URL-адресов. Вопрос, что является допустимым URL, продолжает горячо обсуждаться. Но большинство браузеров применяет сравнительно нестрогий алгоритм проверки. Адрес должен содержать префикс (который может быть как настоящим, типа http://, так и выдуманным, типа bonk//) и позволяет вводить пробелы и большинство специальных символов, за исключением двоеточия.

Некоторые браузеры также предлагают возможные варианты URL в выпадающем списке, которые обычно взяты из журнала недавно посещенных браузером страниц.

Поля поиска

Тип search применяется для полей поиска. Они обычно предназначены для ввода ключевых слов, по которым потом выполняется какой-либо вид поиска. Это может быть поиск по всему Интернету (как в Google), поиск по одной странице или же специальная поисковая процедура, которая исследует каталог информации. В любом случае поле поиска выглядит и ведет себя почти точно так же, как и обычное текстовое поле.

В некоторых браузерах, например Safari, поле поиска выглядит слегка по-другому и имеет скругленные углы. Кроме этого, когда пользователь начинает вводить данные в поле поиска в браузере Safari или Chrome, с правой стороны поля выводится небольшой значок в виде X, щелкнув по которому можно очистить поле.

За исключением этих незначительных различий, поле поиска является ничем иным, как обычным текстовым полем. Основная разница заключается в семантике. Иными словами, тип данных search используется для того, чтобы сделать ясным название поля для браузеров и вспомогательных программ для пользователей с ограниченными возможностями. Они могут направлять посетителей в требуемое место страницы или предоставлять другие, более интеллектуальные услуги — возможно в будущем.

Телефонные номера

Тип данных tel применяется с целью обозначения полей для ввода телефонных номеров, которые могут быть представлены в самых разных форматах. В одних случаях используются только цифры, в других применяются пробелы, тире, знак «плюс» и круглые скобки. Возможно, это отсутствие единого формата и есть причина того, что стандарт HTML5 не требует от браузеров выполнения проверки телефонных номеров. Вместе с тем, не понятно, почему поле типа tel не отклоняет по крайней мере, буквы.

В настоящее время единственная польза от применения поля типа tel состоит в предоставлении специализированной виртуальной клавиатуры для ввода телефонных номеров на мобильных браузерах, которая содержит цифры, но не буквы.

Числа

В HTML5 определяются два числовых типа данных. Тип number предназначен для обычных чисел.

Этот тип данных имеет очевидный потенциал. Обычные текстовые поля принимают буквально все: цифры, буквы, пробелы, знаки пунктуации и т.п. По этой причине одна из самых распространенных задач проверки — убедиться, что значение является числом в определенном диапазоне. Но при вводе данных в поле типа number браузер автоматически игнорирует все символы, кроме цифр. Далее показан пример кода для создания поля этого типа:

Читайте также:  какой номер текущей недели

Обычно поля типа number принимают только целые числа, а дроби, например 30.5 не разрешаются. (Более того, некоторые браузеры даже не позволят ввести десятичный знак.) Но это поведение также можно изменить с помощью атрибута step, который указывает шаг изменения числа (в большую или меньшую сторону). Например, установив значение step в 0.1, можно вводить такие значения, как 0.1, 0.2 0.3 и т. д. Но попробуйте отправить форму со значением 0.15 и вы получите знакомое всплывающее сообщение об ошибке. По умолчанию значение шага равно 1.

Атрибут step также влияет на работу кнопок поля со счетчиком:

Ползунки

Другим числовым типом HTML5 является range. Подобно типу number, этот тип может представлять целые и дробные значения. Также поддерживает атрибуты min и max для установки диапазона значений. Далее показан пример кода для создания поля этого типа:

Разница состоит в том, каким образом поле типа range представляет свою информацию. Вместо счетчика, как для поля типа number, интеллектуальные браузеры отображают ползунок:

Чтобы установить значение типа range, нужно просто перетянуть ползунок в требуемую позицию между минимальным и максимальным значениями. Но браузеры, поддерживающие этот тип поля, не предоставляют никакой обратной информации об установленном значении. Чтобы получить эти сведения, в разметку нужно добавить процедуру JavaScript, которая реагирует на изменения положения ползунка (возможно, посредством обработки события onChange), а потом отображает эту формацию рядом с полем.

Дата и время

В HTML5 определяется несколько типов данных, связанных со временем. Браузеры, которые поддерживают типы дат, могут выводить удобный выпадающий календарь, в котором пользователь может выбрать требуемую дату и/или время. Это не только устраняет неопределенность относительно правильного формата даты, но также запрещает случайно (или нарочно) установить несуществующую дату. Интеллектуальные браузеры могут делать еще больше, например поддерживать интеграцию с персональным календарем.

Ниже показан пример использования дат:

В таблице ниже перечислены шесть новых форматов HTML5 для дат и времени, дано их краткое описание:

Типы данных для дат и времени

Тип данных Описание
date Дата по шаблону ГГГГ-ММ-ДД
time Время в 24-часовом формате с необязательными секундами, по шаблону чч:мм:сс.сс
datetime-local Дата и время, разделенные прописной английской буквой T (по шаблону ГГГГ-ММ-ДДTчч:мм:сс)
datetime Дата и время, как и для типа datetime-local, но со смещением временного пояса. Используется такой же шаблон (ГГГГ-ММ-ДДTчч:мм:сс-чч:мм), как и для элемента
month Год и номер месяца по шаблону ГГГГ-ММ
week Год и номер недели по шаблону ГГГГ-Номер недели

Браузеры, которые поддерживают типы данных для дат и времени, также поддерживают атрибуты min и max для них, что позволяет устанавливать минимальные и максимальные даты при условии использования правильного формата даты. Это продемонстрировано в примере выше.

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

Несколько необычных атрибутов элемента

Стандарт HTML5 признает еще несколько атрибутов, используемых для управления браузером при заполнении форм. Не все эти атрибуты поддерживаются всеми браузерами. Тем не менее, с ними хорошо экспериментировать:

Атрибут spellcheck

Некоторые браузеры пытаются заполнить пробелы в знаниях правописания пользователя, проверяя орфографию вводимого текста. Очевидная проблема с этой услугой заключается в том, что не весь текст состоит из настоящих слов, и роспись волнистых красных подчеркиваний может очень быстро начать действовать пользователю на нервы. Чтобы браузер не проверял орфографию текста в поле, присвойте атрибуту spellcheck значение false, а для проверки — значение true.

По умолчанию разные браузеры действуют по-разному в отношении проверки орфографии, а установка атрибута spellcheck приводит к единообразному поведению.

Некоторые браузеры пытаются сэкономить время пользователя, предлагая при вводе информации в поле значения, которые вводились в это поле ранее. Такое поведение не всегда желательно — как указывается в спецификации HTML5, некоторая информация может быть конфиденциальной (например, коды для запуска ядерных ракет 😉 или оставаться актуальной только непродолжительное время (например, одноразовый пароль входа в банковскую систему самообслуживания). Для таких полей установите значение атрибута autocomplete в off, чтобы браузер не предлагал возможных вариантов завершения вводимого в поле текста. А чтобы выполнять автозаполнение для определенного поля, установите значение его атрибута autocomplete в on.

Атрибуты autocorrect и autocapitalize

Эти атрибуты применяются для управления возможностями автоматического исправления и капитализации на некоторых мобильных браузерах, а именно в версиях Safari для iPad и iPhone

Атрибут multiple

Источник

Input type url для чего

elements of type url are used to let the user enter and edit a URL.

The input value is automatically validated to ensure that it’s either empty or a properly-formatted URL before the form can be submitted. The :valid and :invalid CSS pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid URL or not.

Value

The element’s value attribute contains a DOMString which is automatically validated as conforming to URL syntax. More specifically, there are two possible value formats that will pass validation:

See Validation for details on how URLs are validated to ensure that they’re formatted properly.

Additional attributes

In addition to the attributes that operate on all elements regardless of their type, url inputs support the following attributes.

The values of the list attribute is the id of a element located in the same document. The provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

Читайте также:  какой знак называется кемпинг

maxlength

The input will fail constraint validation if the length of the text value of the field is greater than maxlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

minlength

The input will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user.

pattern

The pattern attribute, when specified, is a regular expression that the input’s value must match in order for the value to pass constraint validation. It must be a valid JavaScript regular expression, as used by the RegExp type, and as documented in our guide on regular expressions; the ‘u’ flag is specified when compiling the regular expression, so that the pattern is treated as a sequence of Unicode code points, instead of as ASCII. No forward slashes should be specified around the pattern text.

If the specified pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely.

Note: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby.

See the section Pattern validation for details and an example.

placeholder

The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.

If the control’s content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

Note: Avoid using the placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Labels and placeholders in : The Input (Form Input) element for more information.

readonly

A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.

Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ( font settings in use).

This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute.

spellcheck

spellcheck is a global attribute which is used to indicate whether or not to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of spellcheck on elements. The permitted values for spellcheck are:

Disable spell checking for this element.

Enable spell checking for this element.

«» (empty string) or no value

Follow the element’s default behavior for spell checking. This may be based upon a parent’s spellcheck setting or other factors.

An input field can have spell checking enabled if it doesn’t have the readonly attribute set and is not disabled.

The value returned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent’s preferences override the setting.

Non-standard attributes

The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can’t be helped.

autocorrect

A Safari extension, the autocorrect attribute is a string which indicates whether or not to activate automatic correction while the user is editing this field. Permitted values are:

Enable automatic correction of typos, as well as processing of text substitutions if any are configured.

Disable automatic correction and text substitutions.

mozactionhint

A Mozilla extension, supported by Firefox for Android, which provides a hint as to what sort of action will be taken if the user presses the Enter or Return key while editing the field. This information is used to decide what kind of label to use on the Enter key on the virtual keyboard.

Using URL inputs

It’s important, however, to note that this is not enough to ensure that the specified text is a URL which actually exists, corresponds to the user of the site, or is acceptable in any other way. It ensures that the value of the field is properly formatted to be a URL.

Note: A user can tinker with your HTML behind the scenes, so your site must not use this validation for any security purposes. You must verify the URL on the server-side of any transaction in which the provided text may have any security implications of any kind.

Читайте также:  ayy что это значит

A simple URL input

Currently, all browsers which implement this element implement it as a standard text input field with basic validation features. In its most basic form, a URL input can be implemented like this:

Notice that it’s considered valid when empty and when a single validly-formatted URL address is entered, but is otherwise not considered valid. By adding the required attribute, only properly-formed URLs are allowed; the input is no longer considered valid when empty.

Placeholders

Controlling the input size

You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself.

Physical input element size

The physical size of the input box can be controlled using the size attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the url edit box is 30 characters wide:

Element value length

The example below creates a 30-character wide URL address entry box, requiring that the contents be no shorter than 10 characters and no longer than 80 characters.

Note: These attributes also affect validation; a value shorter or longer than the specified minimum/maximum lengths will be classified as invalid; in addition most browsers will refuse to let the user enter a value longer than the specified maximum length.

Providing default options

Providing a single default using the value attribute

As always, you can provide a default value for a url input box by setting its value attribute:

Offering suggested values

With the element and its s in place, the browser will offer the specified values as potential values for the URL; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested URLs. Then, as the user types, the list is adjusted to show only matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

Using labels for suggested values

You can opt to include the label attribute on one or all of your elements to provide textual labels. Some browsers may display only the labels, while others may display both the label and the URL.

Validation

There are two levels of content validation available for url inputs. First, there’s the standard level of validation offered to all s, which automatically ensures that the contents meet the requirements to be a valid URL. But there’s also the option to add additional filtering to ensure that your own specialized needs are met, if you have any.

Warning: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.

Basic validation

Browsers that support the url input type automatically provide validation to ensure that only text that matches the standard format for URLs is entered into the input box.

The syntax of a URL is fairly intricate. It’s defined by WHATWG’s URL Living Standard and is described for newcomers in our article What is a URL?

Making a URL required

As mentioned earlier, to make a URL entry required before the form can be submitted (you can’t leave the field blank), you just need to include the required attribute on the input.

Try submitting the above form with no value entered to see what happens.

Pattern validation

If you need the entered URL to be restricted further than just «any string that looks like a URL,» you can use the pattern attribute to specify a regular expression the value must match for the value to be valid.

For example, let’s say you’re building a support page for employees of Myco, Inc. which will let them contact their IT department for help if one of their pages has a problem. In our simplified form, the user needs to enter the URL of the page that has a problem, and a message describing what is wrong. But we want the URL to only successfully validate if the entered URL is in a Myco domain.

First of all, the required attribute is specified, making it mandatory that a valid email address be provided.

This isn’t perfect, but it is good enough for this simple demo’s requirements.

That’s why, instead, we specify the string «The URL must be in a myco domain». By doing that, the resulting full error message might be something like «The entered text doesn’t match the required pattern. The URL should be in a myco domain.»

Note: If you run into trouble while writing your validation regular expressions and they’re not working properly, check your browser’s console; there may be helpful error messages there to aid you in solving the problem.

Examples

There’s not much else to say about url type inputs; check the Pattern validation and Using URL inputs sections for numerous examples.

Источник

Сказочный портал