Html masked input field

Макса ввода для input полей формы HTML

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

А вот для того что бы пользователи заполняли данные формы по определенной маске например номер телефона с кодом пробелами и тире:

Нам поможет плагин masked input.

Для работы плагина необходимо подключение jQuery

Сайт плагина где можно его скачать и познакомится с документацией http://digitalbush.com/projects/masked-input-plugin/.

Настройка masked input

Подключаем jQuery и файл скрипта плагина:

Создаем поле input для например для указания номера телефона и зададим маску ввода:

Создания маски ввода осушествляется в js коде с помощью следующих знаков:

  • Цифра 9 – соответствует цифре от 0 до 9.
  • Символ a – представляет собой любой английский символ (A-Z, a-z).
  • Знак * — представляет собой любой алфавитно-цифровой символ (A-Z, a-z, 0-9).

Так же если вы ходите что бы в качестве маски не указывался знак подчеркивания «_» , можно воспользоваться параметром placeholder:

Так же у данного плагина имеется еще один полезный параметр completed. Он служит для указания действия которое будет выполнено когда пользователь закончит ввод данных по маске. Его можно использовать например что бы ajax запросом проверить наличие данного номера в базе. В примере мы просто вызовем alert и сообщим что именно введено в поле:

Более подробно с возможность плагина можно ознакомится на странице автора MASKED INPUT PLUGIN.

Источник

Input Masking

I don’t have any UX research to cite, but anecdotally, I like it when inputs that expect data in a specific format use an input mask. I thought I’d just line up a few demos for really easy reference.

Robin Herbots’s (jQuery) Inputmask

This is an actively maintained plugin. See the Pen jQuery Input Masks by Chris Coyier (@chriscoyier) on CodePen. It requires the jQuery dependency and the bundled plugin is 180 KB (raw), so it’s fairly hefty.

Estelle Weyl’s Input Masking

Estelle created a vanilla JS version: See the Pen Input Masks by Chris Coyier (@chriscoyier) on CodePen. No dependencies and 5 KB (raw). There is a React component version as well.

I tested the current version of Inputmask, and this is still an issue. Estelle’s version doesn’t do this as the mask is shown via placeholder , not the actual value of the input.

Читайте также:  Java get file from url

Filament Group’s Politespace

Another crack at an accessible version of masking comes from Filament Group. See the Pen Politespace by Chris Coyier (@chriscoyier) on CodePen. It’s different from the others in that you don’t get you use the mask as you are editing the input, it applies formatting after you’ve left it.

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

I tend to like input masking but it’s frustrating when you’re punished for trying to type stuff the “correct” way. Here’s an example with Estelle’s expiration date field: I think a better way to go about it is to let the user input whatever they want, and do all the masking behind the scenes. Here’s a quick example mask for a phone number + extension pulled from an older project of mine:

Gifs didn’t embed 🙁 The preview post button is preeetty misleading sometimes. Here’s Estelle’s: http://i.imgur.com/EHUHB4v.gif
Here’s mine: http://i.imgur.com/2GTyXl1.gif

I’m a huge fan of real-time previews like this instead of in-place masking. Let the user write whatever they want, but show them what the system understands as a “preview before you send” type thing.

Yeah yeah, I could get into that. Feels very nice to have total autonomy over the input itself, while seeing exactly how it’s being interpreted. If there is screen space for it, seems worth it.

It works for certain situations, however dates have so many format that you better show those DD-MM-YYYY as most commonly, date and month are inverted depending of the country

Let’s start a challenge: code a masked (while user is typing) credit card input that triggers the correct numerical keyboard on mobile.

In InputMask’s data field, if I type 0323 , it interprets the 2 as being alone and outputs 03/02/203x . That’s some over-the-top interpretation going on right there. Estelle’s expiration date won’t allow users to place in their own / , which feels pretty weird if you’re trying to type it correctly in the first place. I feel that Filament Group’s is problematic for accessibility as well, as it changes the user’s answer behind the scenes and unless they focus back on the field, they won’t know. This is noticeable for Credit Card and Phone Number: type too many digits, and it cuts off the excess. That might actually matter if the user makes the mistake of placing a country code at the beginning of the phone number when the input didn’t ask for one. I’ve tried writing my own as well, and it’s really, really hard to get these right—especially for assistive technology users. My insights in doing this somewhat well:
– don’t treat auto-formatting as a means to prevent client-side error messages
– don’t replace the value if the value doesn’t need to be replaced (this causes the cursor to jump to the end)
– be very careful about what guesses the auto-formatter asserts (example above in InputMask)
– allow the user to type their own formatting symbols, if those symbols are correct (example above in Estelle’s)
– only inject characters behind the most-recently typed character (this proved to be the least quirky way to hear things in a screen reader), and do not inject a character pre-emptively before the position of the cursor
– do not auto-format at all unless the cursor is positioned at the end, because this replaces the value and causes the cursor to jump to the end, messing up any additional user input. This makes these fields incredibly frustrating to edit (example seen about in Estelle’s—try typing in the day before the month, then “realizing” you got it backwards, deleting the last two digits, and then going back to the front of the string to insert the month first) Overall, my suggestion (especially regarding accessibility) is to just not use them.

I like the mask in the Kendo suite, but it might it would be overkill to add the entire library for just an input mask. I do think they let you add separate js files for just components you want to use, but I think I would still only consider it when using other parts of the library as well. I also agree with James, to not use them, but there are times they are handy. In South Africa, a person’s ID number is 13 digits. There are quite easy ways to validate that on key up, but again if you already have the library, or you are using masks in other places, then it is simple enough to add one. You then already have your first level of validation. Not to then remove other validation, there is always the case that a person blocks JavaScript, but for 90% of the time that validation is there. As well as guidance took the user what you are experiencing.

Читайте также:  Фон в CSS

I’ve always been a fan of sanitizing things quietly, when possible. For US phone numbers, for example, the same field really ought to accept: 5551234567
(555)123-4567
555 123 4567
555-123-4567 It’s rather frustrating when a field requires a certain format out of these things, even if it tells me what that format is. Heck, even when it corrects it for me, I still find it to be more intrusive than letting me type it myself, in my own way. This is especially true if it relies on JavaScript; if a field demands hyphens in a credit card number, even if it adds them as I type, it’s going to fail the moment I try to fill out the form using NoScript. As such, I think we should only be picky on the user-facing end when there’s a functional reason we absolutely must.

Covarr, I use regular expressions to reformat phone numbers after they’re entered, allowing the user to enter as they please. And it covers every format you’ve listed above! All four of your examples are reformatted to (555) 123-4567.

Источник

Маска ввода для полей HTML форм на jQuery

Лучший хостинг для CMS

Маска ввода для полей HTML форм на jQuery

Верстка

В данном уроке мы рассмотрим как с помощью js плагина masked input создавать различные маски ввода для текстовых элементов форм.

Примеры масок созданных при помощи masked input: jsfiddle.net/webrevenue/zfn82pLh/1/

Для того чтобы плагин masked input корректно работал, на вашем сайте должна быть подключена библиотека jQuery.

Подключение masked input

Код приведенный ниже, необходимо подключить к сайту (если у вас уже подключен jQuery, то его подключать не нужно)

Создание HTML маски ввода

Создания маски ввода в js коде осуществляется с помощью следующих знаков:

  • Цифра 9 – соответствует цифре от 0 до 9.
  • Символ a – представляет собой любой английский символ (A-Z, a-z).
  • Знак * — представляет собой любой алфавитно-цифровой символ (A-Z, a-z, 0-9).
Читайте также:  Wordpress редактирование css темы

Пример создания маски ввода телефона для элемента input, имеющего id=»tel»:

В результате получим следующее.

маска ввода для телефона

Больше примеров смотрите здесь: jsfiddle.net/webrevenue/zfn82pLh/1/ .

Источник

Оцените статью