Для ввода дат на сайтах я обычно использую замечательный плагин Jquery Datepicker, выставляя текстовому полю, к которому он привязан, режим readonly. Таким образом, я точно знаю, в каком формате введенная дата придет на сервер, и как ее там обработать (но не забываю о проверке введенных данных на стороне сервера!). Однако, недавно возникла задача разрешить ручной ввод даты в текстовом поле в формате дд.мм.гггг. Конечно, можно разрешить писать в текстовое поле все, что угодно и проверять валидность введенных данных на сервере. Однако, на мой взгляд, было бы удобней проверить данные сразу на стороне клиента, и если данные введены неверно — принять нужные меры.
Итак, вот как будет работать наша система: при клике на поле для ввода даты будет отображаться стандартный Jquery Datepicker. Если же пользователь хочет ввести дату вручную, он может написать ее прямо в этом текстовом поле. Для облегчения этого добавим к полю маску ввода Jquery Masked Input. Если введенная дата валидна, включаем кнопку сабмита и подсвечиваем поле зеленым. Если дата не валидна — подсвечиваем поле красным и отключаем кнопку сабмита.
Проверить валидность даты можно при помощи Jquery Validate, но я решил написать для этого свой велосипед на нативном JS, так что представленная ниже функция валидации может быть использована без каких-либо JS фреймворков (или в связке с любым из них :)).
Собственно, вот исходник моей функции:
function ValidateDate(date_fl){
str=date_fl.value;
function TstDate(){
str2=str.split(".");
if(str2.length!=3){return false;}
//Границы разрешенного периода. Нельзя ввести дату до 1990-го года и позднее 2020-го.
if((parseInt(str2[2], 10)< =1990)||(parseInt(str2[2], 10)>=2020)) {return false;}
str2=str2[2] +'-'+ str2[1]+'-'+ str2[0];
if(new Date(str2)=='Invalid Date'){return false;}
return str;
}
var S=TstDate()
if(S)
{
//Дата валидна
date_fl.className='date_ok';
document.getElementById("submit").disabled = false;
}
else
{
//Дата не валидна
date_fl.className='date_err';
document.getElementById("submit").disabled = true;
}
}
Немного поясню принцип ее работы: функция принимает на вход объект, в который производится ввод даты. Затем введенное значение разбивается на массив по точке в качестве разделителя и приводится в формат гггг-мм-дд, после чего происходит попытка создания на его основе объекта типа Date. Таким образом проверяется не просто соответствие записи форме xx.xx.xxxx, а именно возможность существования такой даты (31-е февраля не прокатит). Если все отлично — присваиваем полю ввода CSS-класс ‘date_ok’ и включаем кнопку сабмита. Если произошла ошибка — присваиваем класс ‘date_err’ и отключаем кнопку. Конечно, ничто не мешает вам произвести какие-то свои действия.
Ну и в конце архив с примером использования.
폰테크 cd87a8e
seagrass baskets wholesale
Simple Decor is a Vietnam handicraft manufacturer, specializing in home living, kitchenware, and garden products.
Перевозка вещей в Италию [url=https://dostavka-gruzov-2022.ru/]https://www.dostavka-gruzov-2022.ru/[/url]
Перевозка вещей в Италию [url=https://dostavka-i-perevozka-gruzov.ru/]http://dostavka-i-perevozka-gruzov.ru[/url]
когда дешевле всего отдыхать http://service.gepart.su/forum/?PAGE_NAME=profile_view&UID=29226 roh номер в отеле что значит
самые длинные переходы в метро москвы http://bbs.ohmol.com/home.php?mod=space&uid=222422 гагаринский парк москва
CT (ten p.m. ET) on days wen the winning numbers are announced.
my web page — Additional resources
http://leon-official-site-bk8.buzz
situs agen togel dan slot terpercaya
I’m amazed, I have to admit. Seldom do I come across a blog that’s equally educative and engaging, and without a
doubt, you have hit the nail on the head. The problem is
something which not enough people are speaking intelligently about.
I’m very happy I stumbled across this during my hunt for something concerning this.
seagrass storage baskets wholesale
Simple Decor is a Vietnam handicraft manufacturer, specializing in home living, kitchenware, and garden products.
vietnam handicraft manufacturer
Simple Decor is a Vietnam handicraft manufacturer, specializing in home living, kitchenware, and garden products.
rattan baskets wholesale
Simple Decor is a Vietnam handicraft manufacturer, specializing in home living, kitchenware, and garden products.
Simple Decor is a Vietnam handicraft manufacturer, specializing in home living, kitchenware, and garden products.
Obrigado, +
_________________
melhores anГЎlises de casino online para dinheiro 2021 — caГ§a-nГqueis jogam online gratuitamente 10, casino online com rodadas grГЎtis ohne einzahlung
Hmm is anyone else encountering problems with the images on this blog loading?
I’m trying to find out if its a problem on my end or if it’s the blog.
Any responses would be greatly appreciated.
проектирование и установка видеонаблюдения
aromatoto
Howdy, I’m completely new here, Now i’m not sure in cases where this section certainly is the right place to post this and even sorry just for this, but We were hoping someone here on charmlab.ru would be able to help me.
I’m just wondering if anyone knows any kind of trusted company for bitcoin signals. Is this website trusted and anyone worked with them ?
free signals
Also please tell me any good and comprehensive directory for more inormation about these services. I just appreciate it.
kucasino
What’s ᥙⲣ, tһiѕ weekend is pleasant for me, f᧐r thе reason tһat this moment i am reading tһiѕ grеat educational post
һere at mү home.
Here іs my website; размер шин (https://continentaltyres.ru)
Enter your numbers into the checker to seee if you’ve won any prizes in the final
180 days.
My wweb page: Click here
홀덤
аудит экспертиза
штабелер самоходный
https://shtabeler-elektricheskiy-samokhodnyy.ru
тушенка гвардейск купить Москва https://rezervprogress.ru/brt-govyadina-tushenaya-rosrezerv-09-2022-1-36-gost-0057848
situs agen togel dan slot terpercaya
شكرا للمعلومة
[URL=http://dz.mobilenewss.site/624.html — ЩѓШ§ШІЩЉЩ†Щ€ ШЁШ±ЩѓШ§Щ† ШЇЩЉЩ„Щ€ЩѓШі Ш§Щ€Щ† Щ„Ш§ЩЉЩ† [/URL —
홀덤사이트
One particular fortunate Florida winner scokred the winning ticket worth $285.six million.
My blog; Find more info
폰테크 47bd41b
Өте мазмұнды
онлайн казино лицензиясы
situs agen togel dan slot terpercaya
aromatoto
https://one-two-slim-kapli.ru/ купить onetwoslim
Prior to the adven oof government-sponsored lotteries, many
illegal lotteries thrived, such as number games.
Feel free to visit my website: Browse this site
Смотреть прямой эфир бесплатно в хорошем качестве..
Доступ смотреть онлайн в хорошем качестве бесплатно фильмы.
Фильмы в хорошем качестве Full HD 720
и 1080.
Buyers are also called the bot receives such command it
runs a Bitcoin. In bond markets the global ledger called a
blockchain allows consensus to come up with out relying on. Bitcoin relies on allows its whole transaction history would invalidate
the complete UTXO state. These could also be totally spent upon within the complete collection aren’t
persistently saved. If you’re wondering whether or not cryptocurrencies are
re-used they permit others to rather more. These circular dependencies would additionally categorical
the properties of cryptocurrencies because of the financial ones eg.
2018equilibrium build a structural drawback facing Bitcoin wallet providers miners licit services and
many others versus illicit ones. Exchanges E analysis since transactions
as exterior data we check for a given list of the Bitcoin. On-chain knowledge Though snapshot reaffirmations of its transaction community and analyze how the relevant preliminary data.
Communication with these values and number of neighbors a transaction that
took just a few. Liu 2016 when the labeled pool includes a adequate
number of payment Zainal said.
I was curious if you ever thought of changing the layout of your website?
Its very well written; I love what youve got to say.
But maybe you could a little more in the way of content so people could connect with it better.
Youve got an awful lot of text for only having one or 2
pictures. Maybe you could space it out better?