- Input type date android
- Значение
- Дополнительные атрибуты
- Использование полей ввода c типом date
- Как использовать date?
- Установка максимальной и минимальной даты
- Controlling input size
- Validation
- Handling browser support
- Examples
- JavaScript
- Input type date android
- Value
- Additional attributes
- Using date inputs
- Basic uses of date
- Setting maximum and minimum dates
- Controlling input size
- Validation
- Handling browser support
- Examples
- JavaScript
Input type date android
Элементы типа date создают поля ввода и позволяют пользователю ввести дату, либо использовать text box для автоматической проверки контента или использовать специальный интерфейс date picker. Возвращаемое значение включает год, месяц, день, но не время. Используйте поля ввода time (en-US) или datetime-local, чтобы вводить время или дату+время соответственно.
Отображение date различается в зависимости от браузера, кроме того не все браузеры поддерживают date . Подробнее см. Browser compatibility. В неподдерживаемых браузерах элемент будет отображаться как обычный .
Исходный код этого интерактивного примера хранится в репозитории GitHub. Если вы хотите внести свой вклад в проект интерактивных примеров, пожалуйста, клонируйте https://github.com/mdn/interactive-examples и отправьте нам запрос на внесение изменений.
Среди браузеров со своим интерфейсом для выбора даты, есть интерфейс браузеров Chrome и Opera, который выглядит так:
В Edge он выглядит так:
А в Firefox выглядит так:
Value | Возвращает DOMString , с датой в формате гггг-мм-дд, или пустую строку |
События | change (en-US) и input (en-US) |
Поддерживаемые атрибуты | autocomplete , list , readonly , and step |
IDL attributes | list , value , valueAsDate , valueAsNumber . |
Методы | select() (en-US) , stepDown() (en-US) , stepUp() (en-US) |
Значение
Возвращает DOMString , представляющий значение даты введённой в input. Вы можете установить значение по умолчанию для элемента с помощью добавления атрибута в value , например:
Помните, что отображаемый формат даты отличается от настоящего значения value – отображаемый формат даты будет выбран, базируясь на региональных параметрах браузера пользователя, тогда как значение value всегда имеет формат гггг-мм-дд .
Вы также можете получить или установить значение даты в JavaScript с помощью свойств value и valueAsNumber элемента input. Например:
Этот код выбирает первый элемент , type которого date и устанавливает значение даты в 2017-06-01 (1 Июня 2017). Затем он считывает это значение обратно в строковом и числовом форматах.
Дополнительные атрибуты
В дополнение к общим атрибутам для всех элементов , у «date» есть следующие дополнительные атрибуты:
Атрибут | Описание |
---|---|
max | Максимально возможная дата для установки |
min | Минимально возможная дата для установки |
step | Шаг (в днях), с которым будет изменяться дата при нажатии кнопок вниз или вверх данного элемента |
Максимально возможная дата для установки. Если value является более поздней датой, чем дата, указанная в атрибуте max , элемент отобразит ошибку при помощи constraint validation. Если в атрибуте max указано значение, не удовлетворяющее формату yyyy-MM-dd , значит элемент не будет иметь максимальной даты.
В атрибуте max должна быть указана строка с датой, которая больше или равна дате, указанной в атрибуте min .
Минимально возможная дата для установки. Если value является более ранней датой, чем дата, указанная в атрибуте min , элемент отобразит ошибку при помощи constraint validation. Если в атрибуте min указано значение, не удовлетворяющее формату yyyy-MM-dd , значит элемент не будет иметь минимальной даты.
В атрибуте min должна быть указана строка с датой, которая меньше или равна дате, указанной в атрибуте max .
Атрибут step – это число, которое определяет точность, с которой задаётся значение, или специальное значение any , описанное ниже. Только значения, кратные шагу ( min , если задано, иначе value , или подходящее стандартное значение, если ни одно из двух не задано) будут корректными.
Строковое значение any означает, что никакое значение шага не задано и допустимо любое значение (в пределах других ограничений, таких как min и max ).
Примечание: Когда значение, введённое пользователем, не подходит под заданное значение шага, user agent может округлить его до ближайшего допустимого значения с приоритетом в большую сторону в том случае, если значение находится ровно посередине шага.
Для полей ввода date значение step задаётся в днях; и является количеством миллисекунд, равное 86 400 000 умножить на значение step (получаемое числовое значение хранится в миллисекундах). Стандартное значение step равно 1, что означает 1 день.
Для полей ввода date указание для step значения any даёт такой же эффект, что и значение 1 .
Использование полей ввода c типом date
На первый взгляд, элемент выглядит заманчиво — он предоставляет лёгкий графический интерфейс для выбора даты, нормализует формат даты, отправляемой на сервер независимо от локальных настроек пользователя. Тем не менее, есть проблемы с в связи с ограниченной поддержкой браузеров.
В этом разделе мы посмотрим на простые, а затем и более сложные способы использования , и позже дадим советы по уменьшению влияния поддержки браузерами (смотрите Handling browser support).
Надеемся, со временем поддержка браузерами станет повсеместной, и эта проблема исчезнет.
Как использовать date?
Самый простой способ использовать — это использовать его с элементами и label , как показано ниже:
Установка максимальной и минимальной даты
Вы можете использовать атрибуты min и max , чтобы ограничить дату, которую может выбрать пользователь. В следующем примере мы устанавливаем минимальную дату 2017-04-01 и максимальную дату 2017-04-30 . Пользователь сможет выбрать дату только из этого диапазона:
В результате выполнения кода, пользователь сможет выбрать любой день апреля 2017 года, но не сможет выбрать и даже просмотреть дни других месяцев и годов, в том числе через виджет date picker.
Примечание: вы должны уметь использовать атрибут step , чтобы менять количество дней, на которое будет происходить шаг при изменении даты (например, чтобы сделать выбираемыми только субботы). Однако, не похоже, что это где-то применялось на данный момент.
Controlling input size
doesn’t support form sizing attributes such as size . You’ll have to resort to CSS for sizing needs.
Validation
By default, does not apply any validation to entered values. The UI implementations generally don’t let you enter anything that isn’t a date — which is helpful — but you can still leave the field empty or (in browsers where the input falls back to type text ) enter an invalid date (e.g. the 32nd of April).
If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you’ll have to check the results to be sure the value is within these dates, since they’re only enforced if the date picker is fully supported on the user’s device.
In addition, you can use the required attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.
Let’s look at an example — here we’ve set minimum and maximum dates, and also made the field required:
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here’s a screenshot for those of you who aren’t using a supporting browser:
Here’s the CSS used in the above example. Here we make use of the :valid and :invalid CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can’t be styled or shown effectively.
Important: 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 simply 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 is submitted (or data which is too large, is of the wrong type, and so forth).
Handling browser support
As mentioned above, the major problem with using date inputs at the time of writing is browser support. As an example, the date picker on Firefox for Android looks like this:
Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
The second problem is the more serious of the two; as we mentioned earlier, with a date input, the actual value is always normalized to the format yyyy-mm-dd . With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there are lots of different ways in which people write dates, for example:
One way around this is to put a pattern attribute on your date input. Even though the date input doesn’t use it, the text input fallback will. For example, try viewing the following example in a non-supporting browser:
If you try submitting it, you’ll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn’t match the pattern nnnn-nn-nn , where n is a number from 0 to 9. Of course, this doesn’t stop people from entering invalid dates, or incorrectly formatted dates, such as yyyy-dd-mm (whereas we want yyyy-mm-dd ). So we still have a problem.
The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the day, month, and year in separate controls ( elements being popular; see below for an implementation), or to use a JavaScript library such as jQuery date picker.
Examples
In this example we create two sets of UI elements for choosing dates: a native picker and a set of three elements for choosing dates in older browsers that don’t support the native input.
The HTML looks like so:
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)
JavaScript
The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports , we create a new element, set its type to date , then immediately check what its type is set to — non-supporting browsers will return text , because the date type falls back to type text . If is not supported, we hide the native picker and show the fallback picker UI ( ) instead.
Note: Remember that some years have 53 weeks in them (see Weeks per year)! You’ll need to take this into consideration when developing production apps.
Источник
Input type date android
elements of type=»date» create input fields that let the user enter a date, either with a textbox that validates the input or a special date picker interface.
The resulting value includes the year, month, and day, but not the time. The time and datetime-local input types support time and date+time input.
The input UI generally varies from browser to browser; see Browser compatibility for further details. In unsupported browsers, the control degrades gracefully to .
Value | A DOMString representing a date in YYYY-MM-DD format, or empty |
Events | change and input |
Supported common attributes | autocomplete , list , readonly , and step |
IDL attributes | list , value , valueAsDate , valueAsNumber . |
Methods | select() , stepDown() , stepUp() |
Value
A DOMString representing the date entered in the input. The date is formatted according to ISO8601, described in Format of a valid date string in Date and time formats used in HTML.
You can set a default value for the input with a date inside the value attribute, like so:
Note: The displayed date format will differ from the actual value — the displayed date is formatted based on the locale of the user’s browser, but the parsed value is always formatted yyyy-mm-dd .
You can get and set the date value in JavaScript with the HTMLInputElement value and valueAsNumber properties. For example:
This code finds the first element whose type is date , and sets its value to 2017-06-01 (June 1st, 2017). It then reads that value back in string and number formats.
Additional attributes
Along with the attributes common to all elements, date inputs have the following attributes.
The latest date to accept. If the value entered into the element occurs afterward, the element fails constraint validation. If the value of the max attribute isn’t a possible date string in the format yyyy-mm-dd , then the element has no maximum date value.
If both the max and min attributes are set, this value must be a date string later than or equal to the one in the min attribute.
The earliest date to accept. If the value entered into the element occurs beforehand, the element fails constraint validation. If the value of the min attribute isn’t a possible date string in the format yyyy-mm-dd , then the element has no minimum date value.
If both the max and min attributes are set, this value must be a date string earlier than or equal to the one in the max attribute.
The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any , which is described below. Only values which are equal to the basis for stepping ( min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid.
A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max ).
Note: When the data entered by the user doesn’t adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.
For date inputs, the value of step is given in days; and is treated as a number of milliseconds equal to 86,400,000 times the step value (the underlying numeric value is in milliseconds). The default value of step is 1, indicating 1 day.
Note: Specifying any as the value for step has the same effect as 1 for date inputs.
Using date inputs
Date inputs sound convenient — they provide an easy interface for choosing dates, and they normalize the data format sent to the server regardless of the user’s locale. However, there are currently issues with because of its limited browser support.
In this section, we’ll look at basic and then more complex uses of , and offer advice on mitigating the browser support issue later (see Handling browser support).
Note: Hopefully, over time browser support will become ubiquitous, and this problem will fade away.
Basic uses of date
The simplest use of involves one combined with its , as seen below:
This HTML submits the entered date under the key bday to https://example.com — resulting in a URL like https://example.com/?bday=1955-06-08 .
Setting maximum and minimum dates
You can use the min and max attributes to restrict the dates that can be chosen by the user. In the following example, we set a minimum date of 2017-04-01 and a maximum date of 2017-04-30 :
The result is that only days in April 2017 can be selected — the month and year parts of the textbox will be uneditable, and dates outside April 2017 can’t be selected in the picker widget.
Note: You should be able to use the step attribute to vary the number of days jumped each time the date is incremented (e.g. to only make Saturdays selectable). However, this does not seem to be in any implementation at the time of writing.
Controlling input size
doesn’t support form sizing attributes such as size . Prefer CSS for sizing it.
Validation
By default, doesn’t validate the entered value beyond its format. The interfaces generally don’t let you enter anything that isn’t a date — which is helpful — but you can leave the field empty or enter an invalid date in browsers where the input falls back to type text (like the 32nd of April).
If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is out of bounds. However, you’ll need to double-check the submitted results to ensure the value is within these dates, if the date picker isn’t fully supported on the user’s device.
You can also use the required attribute to make filling in the date mandatory — an error will be displayed if you try to submit an empty date field. This should work in most browsers, even if they fall back to a text input.
Let’s look at an example of minimum and maximum dates, and also made a field required:
If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
Here’s the CSS used in the above example. We make use of the :valid and :invalid pseudo-elements to add an icon next to the input, based on whether or not the current value is valid. We had to put the icon on a next to the input, not on the input itself, because in Chrome at least the input’s generated content is placed inside the form control, and can’t be styled or shown effectively.
Warning: Client-side form validation is no substitute for validating on the server. It’s easy for someone to modify the HTML, or bypass your HTML entirely and submit the data directly to your server. If your server fails to validate the received data, disaster could strike with data that is badly-formatted, too large, of the wrong type, etc.
Handling browser support
As mentioned, the major problem with date inputs is browser support.
Unsupporting browsers gracefully degrade to a text input, but this creates problems in consistency of user interface (the presented controls are different) and data handling.
The second problem is the more serious one; with date input supported, the value is normalized to the format yyyy-mm-dd . But with a text input, the browser has no recognition of what format the date should be in, and there are many different formats in which people write dates. For example:
One way around this is the pattern attribute on your date input. Even though the date picker doesn’t use it, the text input fallback will. For example, try viewing the following in a unsupporting browser:
If you submit it, you’ll see that the browser displays an error and highlights the input as invalid if your entry doesn’t match the pattern ####-##-## (where # is a digit from 0 to 9). Of course, this doesn’t stop people from entering invalid dates, or incorrect formats. So we still have a problem.
At the moment, the best way to deal with dates in forms in a cross-browser way is to have the user enter the day, month, and year in separate controls, or to use a JavaScript library such as jQuery date picker.
Examples
In this example, we create 2 sets of UI elements for choosing dates: a native picker and a set of 3 elements for older browsers that don’t support the native date input.
The HTML looks like so:
The months are hardcoded (as they are always the same), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year (see the code comments below for detailed explanations of how these functions work.)
JavaScript
The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports .
We create a new element, try setting its type to date , then immediately check what its type is — unsupporting browsers will return text , because the date type falls back to type text . If isn’t supported, we hide the native picker and show the fallback ( ) instead.
Note: Remember that some years have 53 weeks in them (see Weeks per year)! You’ll need to take this into consideration when developing production apps.
Источник