Html input with mask

Маска для полей формы.Маски ввода для текстовых полей

В этой записи я покажу вам плагин который создает маску для поля input . С помощью данного плагина вы сможете сделать маску поля для телефона, даты, или любого другого. Вы можете сделать любую маску. Плагин называется — jquery.maskedinput

Из всего списка файлов нам нужен только jquery.maskedinput.js, который находится в папке dist.

HTML

Здесь нам нужно подключить плагин и библиотеку jquery.

Далее нужно прописать просто тег input , которому нужно указать уникальный id . Этот id мы в дальнейшим будем использовать в jquery скрипте.

JavaScript(jQuery)

JavaScript код необходимо прописать в самом низу HTML кода. Здесь мы прописываем функцию, в которой указываем маску для нашего поля.

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

Дополнительные возможности плагина

Выполнение дополнительного кода после заполнения поля

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

Выбор маски пользователем

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

Для этого нужно изменить HTML код

   

И прописать JavaScript код, который в зависимости от выбранного параметра будет изменять маску для поля.

$(function() < function maskPhone() < var country = $('#country option:selected').val(); switch (country) < case "ru": $("#phone").mask("+7(999) 999-99-99"); break; case "ua": $("#phone").mask("+380(999) 999-99-99"); break; case "by": $("#phone").mask("+375(999) 999-99-99"); break; >> maskPhone(); $('#country').change(function() < maskPhone(); >); >);

Самые популярные варианты масок для полей

HTML

Для телефона 1:  
Для телефона 2:
Для даты:
Для даты(без разделителя):
Число с плавающей точкой:
Число с плавающий точкой(обязательно с "+" или "-" вначале):
Для кода цвета:
Для выбора маски из списка:

JavaScript(jQuery)

 //Для телефона 1 $(function()< $("#phone1").mask("8(999) 999-9999"); >); //Для телефона 2 $("#phone3").mask("8(999) 999-99-99", < completed: function()< alert("Вы ввели номер: " + this.val()); >>); //Для даты $("#date").mask("99.99.9999", ); //Для даты(без разделителя) $("#index").mask("999999", ); //Для числа с плавающей точкой $("#number").mask("0.9?9"); //Для числа с плавающий точкой(обязательно с "+" или "-" вначале) $.mask.definitions['~']='[+-]'; $("#number2").mask("~9.99"); //Для кода цвета $.mask.definitions['h']='[A-Fa-f0-9]'; $("#color").mask("#hhhhhh"); //Для выбора маски из списка: $(function() < function maskPhone() < var country = $('#country option:selected').val(); switch (country) < case "ru": $("#phone").mask("+7(999) 999-99-99"); break; case "ua": $("#phone").mask("+380(999) 999-99-99"); break; case "by": $("#phone").mask("+375(999) 999-99-99"); break; >> maskPhone(); $('#country').change(function() < maskPhone(); >); >);

На этом всё!
Больше интересных статей в нашей группе — https://vk.com/progtime
Вы так же можете разместить свой вопрос на нашем форуме, где другие программисты смогут вам помочь в решение вашей задачи — https://vk.com/prog_time
Так же прокачивайте свои навыки на нашем канале — https://www.youtube.com/c/ProgTime

  • Написание материала для курса по разработке ботов на Telegram
  • Разработка универсального парсера на PHP

Каждый переведённый донат, мотивирует на создание новых записей и уроков на YouTube

Источник

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.

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.

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.

Источник

Примеры шаблонов для использования в input pattern

Более сложная проверка вводимого номера телефона в input-поле с проверкой и подстановкой дополнительных символов:

 
93[\)]\s?\d[-]\d[-]\d" placeholder="+7(___)___-__-__">

HTML Проверка даты

Введите дату в формате дд.мм.гггг:

\.1\.4">

Метод checkValidity() может быть выполнен на любом отдельном поле или формы в целом, вернув true или false – соответствует шаблону или нет.

Источник

Читайте также:  Css селектор по типу
Оцените статью