How to validate user input date is the last day of the month using javascript?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
(Update: See the final example at the bottom, but the rest is left as background.)
You can add a day to the
Dateinstance and see if the month changes (because JavaScript’sDateobject fixes up invalid day-of-month values intelligently), e.g.:Gratuitous live example
…or as paxdiablo pointed out, you can check the resulting day-of-month, which is probably faster (one fewer function call) and is definitely a bit shorter:
Another gratuitous live example
You could embed more logic in there to avoid creating the temporary date object if you liked since it’s really only needed in February and the rest is just a table lookup, but the advantage of both of the above is that they defer all date math to the JavaScript engine. Creating the object is not going to be expensive enough to worry about.
…and finally: Since the JavaScript specification requires (Section 15.9.1.1) that a day is exactly 86,400,000 milliseconds long (when in reality days vary in length a bit), we can make the above even shorter by adding the day as we :
Final gratuitous example