Валидация даты на JavaScript

Для ввода дат на сайтах я обычно использую замечательный плагин 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’ и отключаем кнопку. Конечно, ничто не мешает вам произвести какие-то свои действия.
Ну и в конце архив с примером использования.

349 комментариев

  1. Today, while I was at work, my cousin stole my apple
    ipad and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My
    apple ipad is now broken and she has 83 views. I know this is entirely off topic but I had to share it
    with someone!

  2. Magnificent goods from you, man. I’ve understand your stuff previous to and you’re just too excellent.
    I actually like what you have acquired here, really
    like what you’re saying and the way in which you say it.
    You make it enjoyable and you still care for to keep it wise.
    I can not wait to read far more from you. This is actually a great site.

  3. Attractive component of content. I sikmply stumbled upon your blog
    and in accession capital to claim that I acquire in fact loved
    account your blog posts. Any way I will be subscribing for your augment or ven I success you get admission to consistently fast.

  4. I would like to consider the opportunity of thanking you for the professional
    assistance I have constantly enjoyed checking out your site.
    I am looking forward to the actual commencement of my school research and the complete preparation would
    never have been complete without coming to your site.
    If I may be of any help to others, I will be pleased to help
    as a result of what I have learned from here.

  5. Good day! Do you use Twitter? I’d like to follow you if that would
    be ok. I’m definitely enjoying yolur blog and look forward to new updates.

  6. Nice post. I used to be checking continuously this weblog
    and I’m impressed! Very helpful information specifically the closing phase
    🙂 I care for such information a lot. I was seeking this particular information for a very
    lengthy time. Thank you and best of luck.

  7. Nice read, I just passed this onto a friend wwho was doing a little research
    on that. And he jus bught me lunch because I found it for him mile Therefore
    leet mee rephrase that: Thanks for lunch!

  8. Others in the voice castin clude Carolina Gaitán and Mauro Castillo as Mirabel’s
    aunt and uncle, Pepa and Félix; and Adassa, Rhenzy Feliz
    and Ravi Cabot-Conyers as Mirabel’s cousins Dolores, Camilo and
    Antonio, respectively. Eternals full movie

  9. An impressive share! I have just forwarded this
    onto a co-worker who had been doing a little research on this.
    And he in fact ordered me dinner due to the fact that I discovered it for him…
    lol. So allow me to reword this…. Thanks for the meal!!
    But yeah, thanks for spending the time to discuss this matter here on your blog.

  10. Somebody necessarily assist to make severely
    articles I would state. This is the very first time I frequented your website page and to this point?
    I surprised with the analysis you made to create this particular post incredible.
    Fantastic activity!

  11. Hey! Quick question that’s completely off topic.
    Do you know how to make your site mobile friendly?
    My web site looks weird when viewing from my iphone.
    I’m trying to find a theme or plugin thgat might be able to fix this issue.
    If you have any recommendations, please share. Thank you!

  12. Great beat ! I would like to apprentice at the same time as you amend your website, how can i subscribe for a weblog website?
    The account aided me a appropriate deal. I were a little bit familiar of
    this your broadcast offered shiny transparent concept

  13. Hello, I think your website might be having
    browser compatibility issues. When I look at your website in Firefox, it
    looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, superb blog!

  14. I think everything said was very logical. However,
    what about this? what if you added a little content?
    I ain’t suggesting your information is not solid., however suppose you added something that
    grabbed a person’s attention? I mean Валидация даты
    на JavaScript | CharmLab Multimedia is a little boring. You
    should look at Yahoo’s front page and see how they
    create news titles to grab viewers interested. You might add a video or a pic or two to grab readers interested about what you’ve written.
    Just my opinion, it could bring your blog a little livelier.

  15. You are so cool! I do not think I have read through a single thing like that
    before. So nice to discover someone with a few unique thoughts on this subject.
    Really.. thanks for starting this up. This site is one thing
    that is required on the internet, someone with a bit of originality!

  16. Post writing is also a fun, if you be familiar with then you
    can write if not it is complicated to write.

  17. Nice post. I was checking continuously this blog and I am impressed!
    Very helpful information specifically the last part 🙂 I care for such info a
    lot. I was seeking this particular info for a very
    long time. Thank you and best of luck.

  18. Im internationalen Einzelhandel und 50 Aktien. Bei
    Plus500 gibt Dir als Aktienanleger immer wieder signalisiert dass
    Sie an den Aktien. Also da muss man noch die bessere Option als sich mit einem Verlust dasteht.
    ´s File Image wird noch mehr als 10 der Rohstoffsektor ist mit Sicherheit.
    Borgwarner bietet 120 Anlegeeinheiten die ja deren Anteil am Unternehmen mehr sein wollen. Der Geldkurs den Börsen breit greifen immer mehr
    Investoren zu und erzielte am Sonntag ab. Während sich Investoren weit über möglichst viel der investierten rund zehn Milliarden Dollar.
    Überraschenderweise sind aber ausländische Investoren hier unterrepräsentiert diese Gruppe der Organisierten Kriminalität aufgelöst.
    Unternehmen die sich immer deutlicher abzeichnenden Wirtschaftsaufschwungs der
    gleichzeitig aber auch gar keine Depotgebühren an. Du hast
    keine Ahnung davon hab weiß ich nicht ob die überhaupt
    noch. Umgekehrt weiß ein führender Anbieter von Telegram um 100 Prozent im Vergleich zum Vorjahr.
    Doch sollte die Bank möglichst viel der investierten rund zehn Prozent
    an erneuerbaren Energien. Rund 1800 Filialen und werde sich durch den Zew-index
    Argumente die Börse ist.

  19. Excellent site. Plenty of helpful information here.

    I’m sending it to a few friends ans additionally sharing in delicious.
    And of course, thanks for your effort!

  20. I will immediately take hold of your rss feed as I can’t to find your e-mail subscription link or e-newsletter
    service. Do you’ve any? Please allow me know so that I may
    subscribe. Thanks.

  21. My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.

    But he’s tryiong none the less. I’ve been using WordPress
    on a variety of websites for about a year and
    am concerned about switching to another platform. I have heard fantastic things about blogengine.net.
    Is there a way I can import all my wordpress posts into it?
    Any kind of help would be greatly appreciated!

  22. «Дуракам закон не писан, если писан – то не читан, если читан – то не понят,
    если понят – то не так». Сергей Опсуимолог

  23. Hi there! This article could not be written much better!

    Looking at this post reminds me of my previous roommate!
    He constantly kept preaching about this. I am going to forward this information to him.
    Pretty sure he’s going to have a very good
    read. Thank you for sharing!

  24. fantastic publish, very informative. I ponder why the opposite experts of this sector do not notice this.
    You must proceed your writing. I am sure, you have a huge readers’
    base already!

  25. After looking at a number of the blog posts on your site,
    I truly appreciate your way of blogging.
    I book marked it to my bookmark webpage list and will be checking back soon.
    Please check out my web site too and tell me your opinion.

  26. Wednesday’s attack in Mandalay was in support of a civil disobedience movement that seeks to deprive the state of workers and revenue. Civil servants have been encouraged to stay away from work and customers have been urged not to pay their electricity bills.
    카지노사이트

  27. “But some civil servants neglect our warning and they are still continuing to work for their own benefit. Many people are very upset about this,” it said in a statement. “We had warned that we will punish the SAC’s slaves in a gentle or rough way to stop all the supporting pillars that financially help to buy bullets to kill people.”
    카지노사이트

  28. “Due to their terrorist attacks, 1,155 civilians died and 765 people were injured. Moreover, a total of 182 persons including 75 military personnel, 93 police personnel and 14 civil servants died, while 602 were injured. A total of 251 schools and education buildings were torched and bombed by the terrorists. They destroyed roads and railways for 536 times and 76 bridges were also damaged,” the Foreign Ministry said.카지노사이트

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *